Mutex locks in C#

Mutex is a commonly used thread synchronization mechanism, which is used to ensure that only one thread is accessing shared resources at any time. In C#, you can use the Mutex class to implement mutual exclusion locks. The WaitOne and ReleaseMutex methods provided by the Mutex class can be used to wait for the release of the mutex and release the held mutex, respectively.

The following is a sample code that uses the Mutex class to implement a mutex:

using System;
using System.Threading;

class Program
{
    static Mutex mutex = new Mutex();

    static void Main()
    {
        Thread thread1 = new Thread(DoWork);
        Thread thread2 = new Thread(DoWork);

        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();
    }

    static void DoWork()
    {
        mutex.WaitOne();

        Console.WriteLine("线程{0}正在执行任务...", Thread.CurrentThread.ManagedThreadId);

        Thread.Sleep(1000);

        Console.WriteLine("线程{0}任务执行完毕!", Thread.CurrentThread.ManagedThreadId);

        mutex.ReleaseMutex();
    }
}

In this sample code, the DoWork method is a task that needs to be protected by a mutex. Before entering this method, the thread needs to call the mutex.WaitOne method to wait for the release of the mutex. When the task is completed, it needs to call the mutex.ReleaseMutex method to release Holds the mutex. Using the Mutex class can greatly improve the correctness of the data and the robustness of the code, but excessive use of mutexes can also affect the performance of the program. The use of mutexes needs to be optimized according to the actual situation.

Guess you like

Origin blog.csdn.net/w909252427/article/details/129713431