Use of mutexes in C # multithreaded series

Source: Internet
Author: User

A mutex is a kernel object that is used to ensure that a thread is exclusive of access to a resource, and that the mutex can be used for mutually exclusive access to resources in different processes.

We can think of a mutex as a taxi and a passenger as a thread. Passengers first wait for the bus, then get on the bus and finally alight. When a passenger is in the car, the other passengers are only allowed to get on when he gets off the bus. The same is true of the relationship between a thread and a C # mutex object, where the thread waits for the C # mutex object to be disposed using the Mutex.waitone () method, or if it waits for a C # mutex object to be freed, or if it is not useful by any object, it automatically owns the object Until it calls the Mutex.releasemutex () method to release the object, while other threads that want to get the C # mutex object are waiting.

MSDN Address: Http://msdn.microsoft.com/en-us/library/system.threading.mutex (v=vs.110). aspx

The example on MSDN shows:

usingSystem;usingSystem.Threading;classexample{//Create a new Mutex. The creating thread does not own the mutex.     Private StaticMutex Mut =NewMutex (); Private Const intNumiterations =1; Private Const intNumthreads =3; Static voidMain () {//Create the threads that would use the protected resource.         for(inti =0; i < numthreads; i++) {Thread Newthread=NewThread (NewThreadStart (ThreadProc)); Newthread.name= String.Format ("thread{0}", i +1);        Newthread.start (); }        //the main thread exits, but the application continues to//run until all foreground threads has exited.    }    Private Static voidThreadProc () { for(inti =0; i < numiterations; i++) {Useresource (); }    }    //This method represents a resource it must be synchronized//So, only one thread at a time can enter.    Private Static voidUseresource () {//Wait until it is safe to enter, and does not enter if the request times out.Console.WriteLine ("{0} is requesting the mutex", Thread.CurrentThread.Name); if(Mut. WaitOne ( +) {Console.WriteLine ("{0} have entered the protected area", Thread.CurrentThread.Name); //Place code to access non-reentrant resources here. //simulate some work.Thread.Sleep ( the); Console.WriteLine ("{0} is leaving the protected area", Thread.CurrentThread.Name); //Release the Mutex.Mut.           ReleaseMutex (); Console.WriteLine ("{0} has released the mutex", Thread.CurrentThread.Name); }        Else{Console.WriteLine ("{0} would not acquire the mutex", Thread.CurrentThread.Name); }    }}//The example displays output like the following://Thread1 is requesting the mutex//Thread1 have entered the protected area//Thread2 is requesting the mutex//Thread3 is requesting the mutex//Thread2 would not acquire the mutex//Thread3 would not acquire the mutex//Thread1 is leaving the protected area//Thread1 has released the mutex

When a thread occupies a mutex, the code can write:

Mutex. WaitOne (); Mutex. WaitOne (); Mutex. WaitOne (); Mutex. WaitOne (); .....

WaitOne when this method is called, the system checks to see that the mutex is not being used by any thread and therefore assigns the mutex to the current thread
Thus, even if you continue to invoke WaitOne, there is no effect because the system discovers that the current thread is already occupied and returns directly. In other words, WaitOne is getting
The way the mutex locks. If you call ReleaseMutex then when the thread exits the mutex lock, other threads can come in to apply. But if you call two times
ReleaseMutex then the exception is thrown because the current thread is actually not occupying the lock.

So it can't be written like this:

Mutex. ReleaseMutex (); // If you already possess that OKmutex. ReleaseMutex (); // call a second direct exception

A mutex is a kernel object, so it can be used as a cross-process thread synchronization.

A process can be written like this:

New Mutex (true,"mutex1");

The b process can be written like this:

Mutex mutex = mutex.openexisting ("mutex1")
openexisting This method signature we can often see later that the function is to get an existing kernel object.
The thread synchronization code that gets to the following is consistent with the single process.

Complete.

Use of mutexes in C # multithreaded series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.