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 = , round = ; //开启3个线程,每个线程测试3轮
//阶段控制对象,每一轮完成后打印结果
static Barrier br = new Barrier(threadNum, (b) =>
{
Console.WriteLine(String.Format("第{0}轮测试完成,线程获取互斥体情况如下:",(b.CurrentPhaseNumber+)));
foreach (string enter in enterList)
{
Console.WriteLine(enter);
}
enterList.Clear();
if (b.CurrentPhaseNumber == round-)
{
Console.WriteLine("所有测试完成!");
Console.ReadLine();
}
}); static void Main(string[] args)
{
int i;
Thread t;
for (i = ; i < threadNum; i++)
{
t = new Thread(startTest);
t.Name = "t" + (i+);
t.Start();
}
}
static void startTest(){
int i;
for (i = ; i < round; i++)
{
testMutex();
}
}
static void testMutex()
{
mt.WaitOne();
enterList.Add(String.Format("{0}-线程{1}获取互斥体", DateTime.Now.ToString(), Thread.CurrentThread.Name));
Thread.Sleep();
enterList.Add(String.Format("{0}-线程{1}释放互斥体", DateTime.Now.ToString(), Thread.CurrentThread.Name));
mt.ReleaseMutex();
br.SignalAndWait();
} }
}

C#互斥体——Mutex

上一篇:iframe关闭操作


下一篇:deiban8 sourcelist