C # multi-thread usage 6-collaboration among threads Mutex,

Source: Internet
Author: User

C # multi-thread usage 6-collaboration among threads Mutex,

Mutex is mutually exclusive in the Process of thread collaboration, and the effect is similar to the thread lock.

/// <Summary> // multi-threaded collaboration-Mutex /// </summary> private static void MultiThreadSynergicWithMutex () {Mutex mutex = new Mutex (true ); thread thread1 = new Thread () => {mutex. waitOne (); for (var I = 0; I <5; I ++) {Console. writeLine (I);} mutex. releaseMutex () ;}); Thread thread2 = new Thread () =>{ mutex. waitOne (); for (var I = 5; I <10; I ++) {Console. writeLine (I);} mutex. releaseMutex () ;}); thread1.Start (); thread2.Start (); mutex. releaseMutex ();}

Note:

1. initiallyOwned indicates whether the mutex creation thread has the mutex. True indicates that the creation thread has a mutex lock. Only when ReleaseMutex is called in the creation thread to release the lock can other waiting threads participate in the activity of grabbing the mutex. False indicates that the mutex lock is in the idle state,Other threads waiting for the mutex lock immediately participate in the activity of grabbing the mutex lock.

2. Use the true parameter when creating mutex in the above program. Therefore, mutex. ReleaseMutex () must be executed after other threads are started. If mutex is not released, other threads will wait.

3. mutex. WaitOne () and mutex. ReleaseMutex () must be used in the same way as {}. Otherwise, an exception "Wait for the process to end due to mutex being abandoned" will occur.

4. Compared with monitor, mutex has no function for temporary release. Therefore, once mutex is released, the threads that originally released the resources will participate in the competition for a new round of mutex.

5. In addition to thread synchronization, mutex can also be used for inter-process synchronization. This knowledge remains to be explored ........

Related Article

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.