C# development-Mutex (14.8)

I. Overview

  • The Mutex class in C# is also used for thread synchronization operations. For example, when multiple threads access a resource at the same time, it is guaranteed that only one thread can access the resource at a time.

  • In the Mutex class, the WaitOne() method is used to wait for the resource to be released, and the ReleaseMutex() method is used to release the resource

  • The WaitOne() method will not end until the ReleaseMutex() method is finished.

<!--more-->

Two examples Use thread mutual exclusion to realize the function that each parking space can only park one car at a time 

2.1 Code

<span style="color:#333333">class Program
{
    private static Mutex mutex = new Mutex();
    public static void PakingSpace(object num)
    {
        if (mutex.WaitOne())
        {
            try
            {
                Console.WriteLine("车牌号{0}的车驶入!", num);
                Thread.Sleep(1000);
            }
            finally
            {
                Console.WriteLine("车牌号{0}的车离开!", num);
                mutex.ReleaseMutex();
            }
        }
    }
    static void Main(string[] args)
    {
        ParameterizedThreadStart ts = new ParameterizedThreadStart(PakingSpace);
        Thread t1 = new Thread(ts);
        t1.Start("冀A12345");
        Thread t2 = new Thread(ts);
        t2.Start("京A00000");
    }
}</span>

2.2 Results

 

2.3 Description

It can be seen from the above running effect that after each car enters and leaves, other cars can occupy the parking space, that is, when a thread occupies a resource, other threads do not use the resource

 

Guess you like

Origin blog.csdn.net/Calvin_zhou/article/details/107831409