Mutex mutex of thread synchronization mode

Source: Internet
Author: User

The mutex is very similar to the critical section, where only the thread that owns the mutex can access the shared resource, and the mutex has only one, so it is guaranteed that only one thread can access the shared resource at the same time and that it achieves thread synchronization.

The mutex is more advanced than the critical section and can be named to support thread synchronization across processes. Mutexes are calls to the Win32 API for mutex operations, so different processes under the same operating system can share locks according to the name of the mutex.

Because of this, the operation of the mutex will be more resources, the performance of the critical area is also reduced, in the use of more discretion. It is better to use critical zone performance for in-process thread synchronization.

Using the mutex class in. NET to represent the mutex, using the instance's WaitOne () to prevent the thread from executing to the Get mutex object, ReleaseMutex () releasing the lock resource, let's take a look at the example

class mutextest    {        //creating a Mutex object          private static mutex mutex = new mutex (true,  "My");        //         static void main (String[] args)         {             run ();             console.readline ();        }         //Analog multithreaded Call         public  static void run ()         {             const int count = 2;             var threads = new thread[count];             for  (var i = 0; i < count;  i++)             {                 var ts = new  ThreadStart (Userresource);                 var t = new thread (TS);                 t.Name =  "Thread"  +  (i + 1);                 threads[i] =  t;            }             foreach  (var t in threads)              {                 t.start ();            }             //             console.writeline (String. Format ("Creating thread {0} owns the mutex.",  thread.currentthread.name));             thread.sleep (;    )         mutex. ReleaseMutex ();             console.writeline ( String. Format ("Creating thread {0} releases the mutex.",  thread.currentthread.name));         }        //modifying shared resource values          public static void userresource ()          {            mutex. WaitOne ();             console.writeline (String. Format ("Child thread named {0} owns the mutex.",  thread.currentthread.name) );             thread.sleep (;  )           mutex. ReleaseMutex ();             console.writeline ( String. Format ("Child thread named {0} releases the mutex.",  Thread.CurrentThread.Name));         }    }

A mutex object is a global object that can be constructed with name, as long as name is considered to be the same mutext. The first bool parameter specified at the time of construction also indicates whether the thread that created the mutex object owns the mutex.

If True indicates possession, it must be freed before it can be used by other threads. In the preceding code example, the main thread is required to release the mutex.

First, a mutex object is created by the main thread and owns the mutex object

The main thread then executes, creating 2 threads, and the thread internally uses WaitOne to prevent the thread from continuing until it receives a signal released by the mutex object to gain access to the mutex and continue execution.

After Sleep 1 seconds, the main thread releases the mutex object

The child thread WaitOne obtains the release signal and seizes the mutex ownership, and the winner enters the execution resource code, and the other child now waits until ReleaseMutex to gain ownership of the mutex.

When using a mutex, WaitOne is used to block the execution of the thread until it acquires ownership of the mutex object. You can also specify a block time, a time-out to obtain a mutex ownership failure, a continuation of subsequent code execution, and no release of the mutex.

WaitOne to be used in pairs with ReleaseMutex, get the lock object to remember to release, otherwise it will cause other threads to wait for the state.

Mutex mutex of thread synchronization mode

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.