Mega Code Archive

 
Categories / C# Tutorial / Thread
 

How a Mutex is used to synchronize access to a protected resource

using System; using System.Threading; class Test {     private static Mutex mut = new Mutex();     static void Main()     {         for(int i = 0; i < 5; i++)         {             Thread myThread = new Thread(new ThreadStart(MyThreadProc));             myThread.Name = String.Format("Thread{0}", i + 1);             myThread.Start();         }     }     private static void MyThreadProc()     {         for(int i = 0; i < 4; i++)         {             UseResource();         }     }     private static void UseResource()     {         mut.WaitOne();         Thread.Sleep(500);         mut.ReleaseMutex();     } }