C # object Lock--monitor

Source: Internet
Author: User

There are some static methods inside the monitor that can be used to get the synchronization lock on the object for some process synchronization control operations

The usage and attention points are as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacemytest{classProgram {//a more easily made mistake.//use Monitor to lock an object (that is, a reference type) instead of a value type. When you pass a value type variable to Enter,//It is boxed as an object. If you pass the same variable to Enter again, it is boxed into a separate object, and the thread does not block. Monitor//The code that should be protected is not protected. In addition, when you pass a variable to Exit,//Another individual object is also created. Because the object passed to Exit is different from the object passed to Enter, Monitor//will throw SynchronizationLockException//This is best done with interlocked.        Private Static int_num =1; //you can just pack it.        Private Static Objectnum =_num; Static voidMain (string[] args) {Thread T1=NewThread (NewThreadStart (addnum)); T1. Name="Thread 1"; Thread T2=NewThread (NewThreadStart (addnum)); T2. Name="Thread 2"; T1.            Start (); T2.            Start ();        Console.ReadLine (); }        //|-thread lockobj->|-ready queue with Lock |-wait Queue//ready queue: The thread that tried the lock object//waiting queue: In the waiting,!!!    Not active!!! Thread monitor.wait to the lock object causes the thread to enter the waiting queue//If just call wait does not call pulse, it may cause the thread to enter a deadlock//timeline executed below: T1 get lock--T1 print--2000ms--t1pulse (at this time the wireless thread is waiting for queue, it is invalid)--2000ms--t1 release the lock and enter the waiting queue--//T2 obtains the lock--t2 print--2000ms--t2pulse (at which point the T1 thread waits for the queue, T1 enters the ready queue)--2000ms--t2 releases the lock and enters the waiting queue--//T1 get lock--t1pulse (at this time T2 thread waiting queue, t2 into ready queue)--T1 print--T1 release lock--T1 exit--//T2 get Lock--t2pulse (at this time the wireless path in wait queue, therefore invalid)--t2 print--t2 release lock--T2 exit        Private Static voidAddnum () {Boolean Gotlock=false; Try            {                //monitor.enter (num);//Get exclusive lockMonitor.Enter (NUM,refGotlock); Console.WriteLine (Thread.CurrentThread.Name+ DateTime.Now.ToString () +"——————"+num); //Release the lock and let the thread enter the wait queue until it gets the lock backThread.Sleep ( -); //notifies the waiting thread to enter the ready queue with a lockmonitor.pulse (num); Thread.Sleep ( -);                Monitor.Wait (num);            Monitor.pulse (num); }            finally{Console.WriteLine (Thread.CurrentThread.Name+ DateTime.Now.ToString () +"——————"+num); if(Gotlock) {monitor.exit (num); }            }        }    }}

Operation Result:

Try to get the object lock with the Monitor class. The catch finally process also has a syntax sugar, the lock keyword

C # object Lock--monitor

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.