操作一:在C#中用Mutex类实现线程的互斥
1.创建新C#项目,并将代码“Mutex_C#示例原代码.txt”复制到源文件中。
2.编写一个程序段(在“// Place code to access non-reentrant resources here.”下),
用于完成从0—30的递增并显示。
3.分别观察启用与不启用互斥体输出结果的差异。
4.采用互斥体的结果:
图一:线程互斥
图二:线程交叉
图三:杀死线程
进程被杀死之后:
线程同步:
此次试验所用的代码:
// This example shows how a Mutex is used to synchronize access // to a protected resource. Unlike Monitor, Mutex can be used with // WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
using System;
using System.Threading;
class Test
{
// Create a new Mutex. The creating thread does not own the
// Mutex.
private static Mutex mut = new Mutex();
private const int numIterations = 1;
private const int numThreads = 3;
static void Main()
{
// Create the threads that will use the protected resource.
for (int i = 0; i < numThreads; i++)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
= String.Format("Thread{0}", i + 1);
myThread.Start();
}
Console.Read();
// The main thread exits, but the application continues to
// run until all foreground threads have exited.
}
private static void MyThreadProc()
{
for (int i = 0; i < numIterations; i++)
{
UseResource();
}
}
// This method represents a resource that must be synchronized
// so that only one thread at a time can enter.
private static void UseResource()
{
// Wait until it is safe to enter.
//mut.WaitOne();
Console.WriteLine("{0} has entered the protected area",
);
// Place code to access non-reentrant resources here.
// Simulate some work.
////int num = 0;
////while(true){
//// ++num;
//// if (num > 30) {
//// break;
//// }
//// Console.Write(num + " ");
//// Thread.Sleep(500);
////}
int num = 67;
char c;
while (true)
{
++num;
if(num>100){
break;
}
c = (char)num;
Console.Write(c + " ");
Thread.Sleep(300);
}
Console.Write("\n");
Console.WriteLine("{0} is leaving the protected area\r\n", );
// Release the Mutex.
//注释之后会产生进程交互
//mut.ReleaseMutex();
}
}。