How a Mutex is used to synchronize access to a protected resource : Mutex « Thread « C# / CSharp Tutorial






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();
    }
}








20.20.Mutex
20.20.1.Threading with Mutex
20.20.2.Use a Mutex to control a shared resource against two current threads
20.20.3.Use the Mutex object: WaitOne
20.20.4.Own a Mutex
20.20.5.Name a Mutex
20.20.6.How a Mutex is used to synchronize access to a protected resource