C#多線程開發7:使用Monitor類同步多個線程

來源:互聯網
上載者:User

標籤:monitor.enter   monitor.exit   多線程同步   獨佔鎖   多線程c#   

在《使用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);                        }        }    }}
程式執行結果如所示。

 

 

C#多線程開發7:使用Monitor類同步多個線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.