Home  >  Article  >  Backend Development  >  Detailed code explanation of C#Thread synchronization Mutex

Detailed code explanation of C#Thread synchronization Mutex

黄舟
黄舟Original
2017-03-20 13:15:122012browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn