线程学习(四)Mutex使用

  • 线程使用Mutex

    • Mutex 用于线程同步,也可用进程间同步

      using System;
      using System.Threading;
      
      namespace Pattern03
      {
          class Program
          {
      
              static int thread_num = 5;//线程数
              static AutoResetEvent autoReset = new AutoResetEvent(false);//标记线程池中执行情况
              static Resource resource = new Resource();
      
              static void Main(string[] args)
              {
      
                  for (int i = 0; i < thread_num; i++)
                  {
                      ThreadPool.QueueUserWorkItem(AsyncMethod, i);
                  }
      
                  autoReset.WaitOne();
                  Console.WriteLine("all complete");
      
                  Console.ReadKey();
              }
      
              static void AsyncMethod(object state)
              {
                  resource.Access((int)state);
      
                  if (Interlocked.Decrement(ref thread_num) == 0)//原子性操作变量 thread_num
                  {
                      Console.WriteLine($"线程id:thread_num{Thread.CurrentThread.ManagedThreadId} 调用完成");
                      autoReset.Set();
                  }
              }
      
          }
      
          class Resource
          {
              Mutex mutex = new Mutex();
              public void Access(int Num)
              {
                  mutex.WaitOne();
                  try
                  {
                      //这段代码是线程安全的
      
                      Console.WriteLine($"线程id:{Thread.CurrentThread.ManagedThreadId} start the Accesss method ,num:{Num}");
                      Thread.Sleep(1000);//模拟耗时操作
                      Console.WriteLine($"线程id:{Thread.CurrentThread.ManagedThreadId} stop the Acess method");
      
                      //这段代码是线程安全的
                  }
                  finally
                  {
                      mutex.ReleaseMutex();
                  }
                 
              }
          }
      }
      
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值