在《使用lock语句同步多个线程》的文章中,使用lock语句同步多线程访问临界资源。
使用lock语句的代码如下所示。
private static object o = new object();
lock (o)
{
if (account >= 1000)
{
Thread.Sleep(10);//自动取款机打了个小盹
account -= 1000;
pocket += 1000;
}
}
使用ILDASM工具查看上面代码对应的IL代码:
可以发现:lock语句被解析为调用Monitor类的Enter()方法和Exit()方法。
下面就来介绍一下Monitor类是如何进行多线程同步的。
调用Monitor类的Enter()方法可以获取临界资源的独占锁;而调用Monitor类的Exit()方法会释放独占锁,退出临界区。当一个线程使用独占锁的方式访问资源时,其他线程就不能访问该资源。所以使用Monitor类的Enter()方法和Exit()方法可以确保每次只有一个线程访问临界资源,以达到同步多个线程的目的。
下面使用Monitor类改写《使用lock语句同步多个线程》一文的示例程序。
using System;
using System.Threading;
namespace MonitorExample
{
class Program
{
static object o = new object();
static int account = 1000;//账户
static int pocket = 0;//口袋
static void Main(string[] args)
{
int threadCount = 10;
var threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(DoSafeWork);
threads[i].Start();
}
for (int i = 0; i < threadCount; i++)
{
threads[i].Join();
}
Console.WriteLine("pocket=" + pocket);
}
public static void DoSafeWork()
{
Monitor.Enter(o);
try
{
if (account >= 1000)
{
Thread.Sleep(10);//自动取款机打了个小盹
account -= 1000;
pocket += 1000;
}
}
finally
{
Monitor.Exit(o);
}
}
}
}
程序执行结果如下图所示。