C#多线程开发7:使用Monitor类同步多个线程

在《使用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);            
            }
        }
    }
}
程序执行结果如下图所示。

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值