zoukankan      html  css  js  c++  java
  • C#互斥体——Mutex

    Mutex对象是一个同步基元,可以用来做线程间的同步。

    若多个线程需要共享一个资源,可以在这些线程中使用Mutex同步基元。当某一个线程占用Mutex对象时,其他也需要占用Mutex的线程将处于挂起状态。

    示例代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace myTest
    {
        class Program
        {
            static List<string> enterList = new List<string>();//用来记录结果
            static Mutex mt = new Mutex();//创建一个同步基元
            static int threadNum = 3, round = 3; //开启3个线程,每个线程测试3轮
            //阶段控制对象,每一轮完成后打印结果
            static Barrier br = new Barrier(threadNum, (b) =>
               {
                   Console.WriteLine(String.Format("第{0}轮测试完成,线程获取互斥体情况如下:",(b.CurrentPhaseNumber+1)));
                   foreach (string enter in enterList)
                   {
                       Console.WriteLine(enter);
                   }
                   enterList.Clear();
                   if (b.CurrentPhaseNumber == round-1)
                   {
                       Console.WriteLine("所有测试完成!");
                       Console.ReadLine();
                   }
               }); 
            
            static void Main(string[] args)
            {
               int i;
               Thread t;
               for (i = 0; i < threadNum; i++)
               {
                   t = new Thread(startTest);
                   t.Name = "t" + (i+1);
                   t.Start();
               }
            }
            static void startTest(){
                int i; 
                for (i = 0; i < round; i++)
                {
                    testMutex();
                }
            }
            static void testMutex()
            {
                mt.WaitOne();
                enterList.Add(String.Format("{0}-线程{1}获取互斥体", DateTime.Now.ToString(), Thread.CurrentThread.Name));
                Thread.Sleep(1000);
                enterList.Add(String.Format("{0}-线程{1}释放互斥体", DateTime.Now.ToString(), Thread.CurrentThread.Name));
                mt.ReleaseMutex();
                br.SignalAndWait();
            }
            
        }
    }

  • 相关阅读:
    .net 笔试面试总结(3)
    .net 笔试面试总结(2)
    .net 笔试面试总结(1)
    依赖注入
    ssh远程连接vm 安装的ubuntu
    ubuntu 安装vm-tool
    go调度: 第二部分-go调度器
    go调度: 第一部分-OS调度(操作系统调度)
    thrift简单示例 (go语言)
    thrift简单示例 (基于C++)
  • 原文地址:https://www.cnblogs.com/tzyy/p/4794969.html
Copyright © 2011-2022 走看看