In the article "Synchronizing multiple threads with the lock statement," Use the lock statement to synchronize access to the critical resource in multithreaded threads.
The code that uses the lock statement is as follows.
Private static Object o = new Object (); Lock (o) { if (account >=) { thread.sleep (10);//cash machine took a nap. Account- =-N; Pocket + + +; }}
Use the ILDASM tool to view the IL code corresponding to the above code:
It can be found that the lock statement is resolved to invoke the Enter () method and the exit () method of the Monitor class.
Let's look at how the Monitor class synchronizes multithreading.
The Enter () method of the Monitor class is called to obtain an exclusive lock on the critical resource, and the exit () method that invokes the Monitor class releases the exclusive lock and exits the critical section. when a thread accesses a resource by using an exclusive lock, other threads cannot access the resource. So using the Monitor class's Enter () method and the exit () method ensures that only one thread accesses the critical resource at a time to achieve the purpose of synchronizing multiple threads.
The following is a sample program that uses the monitor class to override the "Synchronize multiple threads with lock statement" article.
Using system;using system.threading; Namespace monitorexample{class Program {static object o = new Object (); static int account = 1000;//accounts static int pocket = 0;//pocket 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 >=) {thread.sleep (10);//ATMs have a little nap. Account-= 1000; Pocket + = 1000; }} finally {Monitor.Exit (o); } } }}
The program execution results are as shown.
C # multithreaded Development 7: Synchronizing multiple threads with the Monitor class