• 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();
            }
            
        }
    }

  • 相关阅读:
    通过 VB5 创建 ActiveX DLL 文件并用 ASP 调用一例
    Autocad VBA初级教程
    自学资料第一集
    Linux虚拟化:10个不得不爱的理由
    EXCEL VBA编程的一些小结
    FAQ 工作薄及工作表
    很重要的EXCEL使用技巧
    Excel VBA编程的常用代码
    VBA生成一个CorelDraw工具栏
    支付宝,网银在线,快钱 3大支付接口的集成与对比,统合实现
  • 原文地址:https://www.cnblogs.com/tzyy/p/4794969.html
Copyright © 2020-2023  润新知