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 ........