標籤: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類同步多個線程