C # thread Series Lectures (5): Monitor for synchronization technology

Source: Internet
Author: User
In the previous section, we introduced how to use lock to synchronize threads. In fact, this lock is a barrier of C #. When the C # compiler compiles the lock statement, it is compiled into the Monitor class. Let's take a look at the following C # source code: Public static void MyLock ()
{
Lock (typeof (Program ))
{
}
}


The above Code uses the lock statement to synchronize MyLock. After this method is compiled into IL, code 1 is shown.

Figure 1

From the labeled area, we can see that a lock statement is compiled into the Enter and Exit methods that call Monitor. Monitor is in the System. Threading namespace. The lock function is equivalent to directly calling the Monitor Entry method. The difference is that the lock method is automatically unlocked after the lock method ends. Of course, in IL, the Monitor Exit method is called, but in C # program, it seems to be automatically unlocked. This is similar to the using statement in C #, which can automatically release resources such as databases. However, if you directly use the Monitor class in the C # source program, you must call the Exit method to explicitly unlock the lock. The following code is used:

Monitor. Entry (lockObj );
Try
{
// Same layout of lockObj
}
Catch (Exception e)
{
// Exception Handling Code
}
Finally
{
Monitor. Exit (lockObj); // unlock
}

The Exit method is finally called in finally. In this way, the finally method is executed no matter the method is abnormal, returned, or executed normally, and the Exit method is called to unlock the lock.

The Monitor class can not only completely replace the lock Statement (if you only use the function of the lock statement itself, you 'd better use the lock statement directly), but also set a lock timeout using the TryEntry method, the Unit is milliseconds. The following code is used:

If (Monitor. TryEntry (lockObj, 1000 ))
{
Try
{
}
Finally
{
Monitor. Exit (lockObj );
}
}
Else
{
// Processing code after timeout
}

 

The above Code sets the lock timeout time to 1 second, that is, after 1 second, lockObj has not been unlocked, The TryEntry method will return false, if within 1 second, lockObj is unlocked, and TryEntry returns true. We can use this method to avoid deadlocks, as shown in the following code:

Class Program
{
Private static Object objA = new Object ();
Private static Object objB = new Object ();
Public static void LockA ()
{
If (Monitor. tryenter( objA, 1000 ))
{
Thread. Sleep (1000 );
If (Monitor. TryEnter (objB, 2000 ))
{
Monitor. Exit (objB );
}
Else
{

Console. WriteLine ("LockB timeout ");
}
Monitor. Exit (objA );
}
Console. WriteLine ("LockA ");
}
Public static void LockB ()
{
If (Monitor. TryEnter (objB, 2000 ))
{
Thread. Sleep (2000 );
If (Monitor. tryenter( objA, 1000 ))
{
Monitor. Exit (objA );
}
Else
{
Console. WriteLine ("LockA timeout ");
}
Monitor. Exit (objB );
}
Console. WriteLine ("LockB ");
}
Public static void Main ()
{
Thread threadA = new Thread (LockA );
Thread threadB = new Thread (LockB );
ThreadA. Start ();
ThreadB. Start ();
Thread. Sleep (4000 );
Console. WriteLine ("End of thread ");
}
}

 

The above code is an example of a deadlock in the previous article, but in this article, the lock statement is changed to the TryEntry method and the lock timeout is set, the TryEntry method returns regardless of whether the locked object is unlocked. Therefore, the above Code will not be deadlocked. Result 2 of running the above Code is shown.

Figure 2

If the time-out time of the TryEntry method is System. Threading. Timeout. Infinite, The TryEntry method is equivalent to the Entry method. If the time-out time is 0, the TryEntry method will return immediately no matter whether it is unlocked or not.

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.