C # considerations for lock statements in multi-thread programming

Source: Internet
Author: User

From: http://hi.baidu.com/oohacker/blog/item/6004e6fb712feb254e4aea24.html

 

 

The discussion about the C # lock statement is much said on the Internet, but the vast majority only talk about how to use it, but there are few considerations for lock, especially about lock (this ), the discussion of lock (typeof (ClassName) and lock ("thisLock") is even more rare. Even the three locks mentioned above in MSDN may cause problems with one stroke (http://msdn.microsoft.com/zh-cn/worldwide/c5kehkcz.aspx ). Baidu and Google have finally collected relevant information for a long time. Today, I will write it down and share it with you.

The following problems may occur if you do not pay attention to lock:

1) if the instance can be accessed by the public, the lock (this) problem will occur.

2) If MyType can be accessed by the public, the lock (typeof (MyType) problem will occur.

3). Any other code that uses the same string in the process will share the same lock, so the lock ("myLock") problem occurs.

We will discuss these issues as follows:

First, let's look at the lock (this) problem. If a class is public, avoid using the lock (this) Statement in the base method or attribute, because if someone else uses your component, it doesn't know whether the lock is used inside your component,If a user attempts to lock a class instance outside the class, a deadlock may occur,Below is what I got from Google (original address: http://www.toolazy.me.uk/template.php? Content = lock (this) _ causes_deadlocks.xml, because the main thread is sleep in the original program, the actual operating system will automatically switch to the available thread, so it does not reflect the deadlock effect) the modified example is as follows:

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;

Namespace Test
{
Class InternalClass
{
Public void TryLockThis ()
{
Thread t = new Thread (ThreadFunction );
T. Start ();
}

Private void ThreadFunction ()
{
Thread. Sleep (3000); // latency, waiting for the external lock on the object instance
Console. WriteLine ("try to lock the following code block through lock (this ...");

While (true)
{
Lock (this)
{
Console. WriteLine ("execute the internal lock, continue after 1 second ...");
Thread. Sleep (1000 );
Console. WriteLine ("Internal lock completed ...");
}
}
}
}

Class ClassMain
{
Private InternalClass theClass = new InternalClass ();

Public ClassMain ()
{
TheClass. TryLockThis ();
Console. WriteLine ("lock the object before executing the internal lock ...");
Lock (theClass) // If you comment out this sentence, the lock in ThreadFunction () will be successfully executed.
{
Console. WriteLine ("the object is locked. Here we get a deadlock ...");

While (true ){}
}
}

[STAThread]
Static void Main (string [] args)
{
ClassMain cm = new ClassMain ();

Console. WriteLine ("Press Enter to exit ");
Console. ReadLine ();
}
}
}

We can see that the above program will lead to a deadlock, and the execution result of the program is as follows:

Lock the object before executing the internal lock...
The object is locked. Here we get a deadlock...
Try to lock the following code block through lock (this...

Therefore, try to avoid or even reject statements such as lock (this.

Similarly, lock (typeof (ClassName) has a similar problem. Because the typeof statement returns a class type instance, there is only one class, if a typeof (className) statement is used in the class method or instance method, and the class is locked outside the class, a deadlock may also occur.

The lock ("thisLock") problem is caused by the. Net string processing mode.
[MSDN]
The Common Language Runtime library stores strings by maintaining a table, which is called a detention pool and contains a reference to each unique string that is declared or created programmatically in the program. Therefore, there is only one instance of a string with a specific value in the system.
For example, if the same string is assigned to several variables, the runtime will retrieve the same reference to the string from the detention pool and allocate it to each variable.

For this reason, if the string object you lock is in the detention pool (usually the character string explicitly declared during compilation caused by quotation marks), then, this object may also be assigned to another variable. If the variable also uses lock, the two lock statements lock different objects on the surface, but in essence they are the same object, this will cause unnecessary blocking and may even cause deadlocks. No problems are found.

The following program shows a problem:
String a = "String Example ";
String B = "String Example ";
String c = (new StringBuilder (). Append ("String Example"). ToString ();
Console. WriteLine ("a = B? {0} ", object. ReferenceEquals (a, B ));
Console. WriteLine ("a = c? {0} ", object. ReferenceEquals (a, c ));

The execution result of the above program is:
A = B? True
A = c? False

From the above, we can see that a and B point to the same reference, and lock distinguishes and locks the critical code segment through reference. That is to say, if lock ("thisLock") is used in one part of our program, and lock ("thisLock") is also used in another position of the program, it is very likely to cause a deadlock, and thus very dangerous. In fact, statements such as lock ("thisLock") may cause deadlocks when using string-type references in lock.

The above is why the use of lock (this), lock (typeof (className), lock ("thisLock") should be avoided in C.

 

 

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.