C # Threading Series Lectures (5): Monitor of synchronization technology

Source: Internet
Author: User

in the previous session, we introduced the use of lock to achieve synchronization between threads. In fact, this lock is a fake in C #, compiled into a call to the Monitor class when the C # compiler compiles the lock statement . Let's look at the following C # source code:

Public Static voidMyLock ()
{
Lock (typeof(program))
{
}
}


The above code synchronizes the MyLock with the lock statement , which is compiled into IL , as shown in code 1 .



Figure 1

    as you can see from the area being labeled, aLockstatement is compiled into a callMonitorof theEnterand theExitmethod. Monitorin theSystem.Threadingnamespace. Lockfunction is equivalent to calling directlyMonitorof theEntrymethod, the difference is thatLockThe method is automatically unlocked after the end of theILis called in theMonitorof theExitmethod, but inC#program, it appears to be automatically unlocked, which is similar toC#in theUsingstatement, you can automatically release resources such as databases. But if directly inC#used in the source programMonitorclass, you must call theExitmethod to explicitly unlock the lock. As shown in the following code:

monitor.entry (lockobj);
Try
{
//Lockobj in the same area
}
Catch(Exception e)
{
//Exception handling Code
}
finally
{
Monitor.Exit (Lockobj); //Release Lock
}


Exit The method is finally called in Finally, so that no matter whether the method is in an exception, returns, or executes normally, it executes to finally, and calls the Exit method to unlock the lock.

Monitor class can not only completely replace the lock statement (if you only use the function of the lock statement itself, preferably with the lock statement), you can also use the Tryentry method to set a lock timeout in milliseconds. As shown in the following code:

if(Monitor.tryentry (Lockobj, +))
{
Try
{
}
finally
{
Monitor.Exit (Lockobj);
}
}
Else
{
//processing code after time-out
}

The above code sets the lock timeout to 1 seconds, that is , after 1 seconds,the lockobj is not unlocked, andthe Tryentry method returns Falseif lockobj is unlocked within 1 seconds, Tryentry returns true. We can use this method to avoid deadlocks, as shown in the following code:

    classProgram
{
Private StaticObject Obja= NewObject ();
Private StaticObject OBJB= NewObject ();
Public Static voidLocka ()
{
if(Monitor.TryEnter (Obja, +))
{
Thread.Sleep ( +);
if(Monitor.TryEnter (OBJB, -))
{
Monitor.Exit (OBJB);
}
Else
{

Console.WriteLine ("lockb Timeout");
}
Monitor.Exit (Obja);
}
Console.WriteLine ("Locka");
}
Public Static voidlockb ()
{
if(Monitor.TryEnter (OBJB, -))
{
Thread.Sleep ( -);
if(Monitor.TryEnter (Obja, +))
{
Monitor.Exit (Obja);
}
Else
{
Console.WriteLine ("Locka Timeout");
}
Monitor.Exit (OBJB);
}
Console.WriteLine ("lockb");
}
Public Static voidMain ()
{
Thread Threada= NewThread (Locka);
Thread threadb= NewThread (LOCKB);
Threada.start ();
Threadb.start ();
Thread.Sleep (4000);
Console.WriteLine ("Thread End");
}
}

The above code is an example of a deadlock in the previous talk, but in this case the lock statement is changed to the tryentry method, and the lockout timeout is set, because after waiting for a certain amount of time, regardless of whether the locked object is unlocked ,the Tryentry method returns, so the above code is not deadlocked. Run the above code as shown in result 2 .



Figure 2

If the time-out for the Tryentry method is System.Threading.Timeout.Infinite,the Tryentry method is equivalent to Entry method, if the time-out is 0, the Tryentry method returns immediately,regardless of whether it is unlocked .



C # Threading Series Lectures (5): Monitor of synchronization technology

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.