码迷,mamicode.com
首页 > Windows程序 > 详细

C#互斥体——Mutex

时间:2015-09-09 16:25:27      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

C#互斥体——Mutex

标签:

原文地址:http://www.cnblogs.com/tzyy/p/4794969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!