Mega Code Archive

 
Categories / C# / Thread
 

Illustrates the use of the Mutex object

/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /*   Example14_11.cs illustrates the use of the Mutex object */ using System; using System.Threading; public class Example14_11  {   // a shared counter   private static int Runs = 0;   // a mutex   static Mutex mtx;   // the CountUp method increments the shared counter   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()    {     // create the mutex     mtx = new Mutex(false, "RunsMutex");     // create and launch two threads     Thread t2 = new Thread(new ThreadStart(CountUp));     t2.Name = "t2";     Thread t3 = new Thread(new ThreadStart(CountUp));     t3.Name = "t3";     t2.Start();     t3.Start();   } }