当两个或多个进程需要请求共享资源时,如果想限制仅限一个进程,可以使用 Mutex,仅第一个线程独占访问权限,第二个线程进入等待,直到第一个进程释放权限
// 基本语法
private static Mutex mut = new Mutex();
mut.WaitOne(1000); // 获取互斥体
mut. ReleaseMutex ; // 释放互斥体
实例方法thread1以及thread2 中都对a字段赋值
class Program
{
public static int a = 0;
public static void thread1()
{
while (true)
{
a = 100;
Console.WriteLine("thread1 return value of a = {0}", a);
Thread.Sleep(500);
a++;
Console.WriteLine("thread1 return value of a = {0}", a);
}
}
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(thread1));
thread.Start();
while (true)
{
a = 1;
Console.WriteLine("--thread2 return value of = {0}", a);
Thread.Sleep(500);
a++;
Console.WriteLine("--thread2 return value of a = {0}", a);
}
}
}
// 输出结果
//--thread2 return value of = 1
//thread1 return value of a = 100
//thread1 return value of a = 101
//thread1 return value of a = 100
//--thread2 return value of a = 102
//--thread2 return value of = 1
//--thread2 return value of a = 2
//thread1 return value of a = 3
//thread1 return value of a = 100
//--thread2 return value of = 1
thread2 在遇到第一个sheep时被睡眠了,转到thread1中执行,也同样被睡眠,此时a的值取到101,然后0.5秒后thread2苏醒,自加得到值102,并不是如预期那样thread1,100,101循环输出
using System;
using System.Diagnostics.Metrics;
using System.Threading;
namespace mutex_test
{
class Program
{
public static int a = 0;
// Mutex 的 name 要唯一
public static Mutex mutex = new Mutex();
public static void thread1()
{
while (true)
{
mutex.WaitOne();
a = 100;
Console.WriteLine("thread1 return value of a = {0}", a);
Thread.Sleep(500);
a++;
Console.WriteLine("thread1 return value of a = {0}", a);
mutex.ReleaseMutex();
}
}
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(thread1));
thread.Start();
while (true)
{
mutex.WaitOne();
a = 1;
Console.WriteLine("--thread2 return value of = {0}", a);
Thread.Sleep(500);
a++;
Console.WriteLine("--thread2 return value of a = {0}", a);
mutex.ReleaseMutex();
}
}
}
// 输出结果
--thread2 return value of = 1
--thread2 return value of a = 2
thread1 return value of a = 100
thread1 return value of a = 101
--thread2 return value of = 1
--thread2 return value of a = 2
thread1 return value of a = 100
thread1 return value of a = 101
}
添加互斥锁后,thread2获取互斥锁,在未释放前,thread1没有访问权限进入等待