First Mutx m = new Mutex();
In a function m.WaitOne();
Then m.ReleaseMutex ();
Same as m.WaitOne();
m.ReleaseMutex();
You want to write code that can only be accessed by one process The section is placed between m.WaitOne(); and m.ReleaseMutex();
private Mutex mutF = new Mutex(); private Mutex mutH = new Mutex(); private void ReadF() { mutF.WaitOne(); // your code to access the resource mutF.ReleaseMutex(); } private void ReadH() { mutH.WaitOne(); // your code to access the resource mutH.ReleaseMutex(); } private void Form1_Load(object sender, EventArgs e) { Thread tF = new Thread(new ThreadStart(ReadF)); Thread tH = new Thread(new ThreadStart(ReadH)); tFlower.Start(); tH.Start(); mutF.WaitOne(); mutH.WaitOne(); // your code to access the resource Thread.Sleep(1000); mutH.ReleaseMutex(); mutF.ReleaseMutex(); }
The above is the detailed content of Detailed code explanation of C#Thread synchronization Mutex. For more information, please follow other related articles on the PHP Chinese website!