Use the Mutex object : Mutex : Thread C# Examples


C# Examples » Thread » Mutex »

 

Use the Mutex object









    
using  System;
using  System.Threading;

class  MainClass
{
    private  static  int  Runs  =  0;

    static  Mutex  mtx  =  new  Mutex(false,  "RunsMutex");

    public  static  void  CountUp()  
    {
        while  (Runs  <  10)
        {
            //  acquire  the  mutex
            mtx.WaitOne();
            int  Temp  =  Runs;
            Temp++;
            Console.WriteLine(Thread.CurrentThread.Name  +  "  "  +  Temp);
            Thread.Sleep(1000);
            Runs  =  Temp;
            //  release  the  mutex
            mtx.ReleaseMutex();
        }  
    }

    public  static  void  Main()  
    {
        Thread  t2  =  new  Thread(new  ThreadStart(CountUp));
        t2.Name  =  "t2";
        Thread  t3  =  new  Thread(new  ThreadStart(CountUp));
        t3.Name  =  "t3";
        t2.Start();
        t3.Start();
    }
}
    
   
  
   



Output

t2 1
t3 2
t3 3
t3 4
t3 5
t3 6
t3 7
t3 8
t3 9
t3 10
t2 11


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Thread
» Mutex