首页  >  文章  >  后端开发  >  C#Thread同步Mutex的代码详解

C#Thread同步Mutex的代码详解

黄舟
黄舟原创
2017-03-20 13:15:122012浏览

 首先Mutx m = new Mutex();

在一个函数中 m.WaitOne();

然后 m.ReleaseMutex();

在另一个函数中 同样 m.WaitOne();

m.ReleaseMutex();

你要写的只能一个进程访问的代码段就放在m.WaitOne();和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();  
}

以上是C#Thread同步Mutex的代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn