Mutex)
A mutex lock is a mutex synchronization object, which means that only one thread can obtain it at a time.
The mutex lock can be used when a shared resource can be accessed by only one thread at a time.
Function:
// Create an unobtained mutex lock
Public mutex ();
// If owned is true, the initial state of the mutex lock is obtained by the main thread; otherwise, the lock is in the unobtained state.
Public mutex (bool owned );
If you want to obtain a mutex lock. The waitone () method of mutex lock should be called. This method inherits from the thread. waithandle class.
It is in the wait state until the called mutex lock can be obtained. Therefore, this method will hold the main thread until the specified mutex lock is available. If no mutex lock is required, release it using the releasemutex method, so that the mutex lock can be obtained by another thread.
?
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyTTCon { class shareRes { public static int count = 0; public static Mutex mutex = new Mutex(); } class IncThread { int number; public Thread thrd; public IncThread(string name, int n) { thrd = new Thread(this.run); number = n; thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name + "Waiting for the mutex"); // Apply shareRes.mutex.WaitOne(); Console.WriteLine(thrd.Name + "Apply to the mutex"); do { Thread.Sleep(1000); shareRes.count++; Console.WriteLine("In " + thrd.Name + "ShareRes.count is " + shareRes.count); number--; } while (number > 0); Console.WriteLine(thrd.Name + "Release the nmutex"); // Release shareRes.mutex.ReleaseMutex(); } } class DecThread { int number; public Thread thrd; public DecThread(string name, int n) { thrd = new Thread(this.run); number = n; thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name + "Waiting for the mutex"); // Apply shareRes.mutex.WaitOne(); Console.WriteLine(thrd.Name + "Apply to the mutex"); do { Thread.Sleep(1000); shareRes.count--; Console.WriteLine("In " + thrd.Name + "ShareRes.count is " + shareRes.count); number--; } while (number > 0); Console.WriteLine(thrd.Name + "Release the nmutex"); // Release shareRes.mutex.ReleaseMutex(); } } class Program { static void Main(string[] args) { IncThread mthrd1 = new IncThread("IncThread thread ", 5); DecThread mthrd2 = new DecThread("DecThread thread ", 5); mthrd1.thrd.Join(); mthrd2.thrd.Join(); } } } |