Example of lock deadlock in C # tutorial

Source: Internet
Author: User

In C # there is a keyword lock, its role is to lock a block of code, so that only one thread at a time to access the code block, this article to talk about the lock keyword principle and some of the issues should be noted:


The usage prototypes for lock are:

Lock (X) {  //code to be locked ....}

The first thing to understand is why the above paragraph can lock the code, the secret of which is the X object, in fact, X is any kind of reference type, it is the role of any thread execution to lock (x), X needs to be exclusive to run the following code, if it is assumed that there are now 3 threads A, B, C is executed to lock (x) and ABC because at this time has X, then ABC will stop to line up a team, one using X, thereby playing in the following code block only one thread is running (because at this time only one thread exclusive x, the remaining two are queued), So this x must be a resource that must be shared by all of the critical region code processes, thereby suppressing the role of the thread.

Let's talk about the problems you will encounter and pay attention to in lock use, and one of the most important things to remember about lock is thread deadlock!

3 Typical issues are listed on MSDN:

In general, you should avoid locking the public type, or the instance will go beyond the control of your code. Common structure Lock (this), Lock (typeof (MyType)) and lock ("MyLock") violate this guideline:


If the instance can be accessed publicly, the lock (this) issue occurs.


If MyType can be accessed publicly, a lock (typeof (MyType)) issue will occur.


The Lock ("MyLock") issue occurs because any other code that uses the same string in a process will share the same lock.


The best practice is to define private objects to lock, or private shared object variables to protect data that is common to all instances.


(1) lock (this) question:

Suppose there are two classes:

Class A{}class b{}

There are two common objects:

A a=new a (); b b=new B ();

First, in a the code within a function needs to be locked:

Code Listing 1:

Lock (This)//this here is a{//.... Lock (b) {//...}}

However, at this point a function in B also has the following code to lock:

Code Listing 2:

Lock (This)//this here is b{//.... Lock (a) {//...}}

Imagine what happens if the above two pieces of code execute simultaneously under two threads.

As a result, code 1 executes to lock (this) after a is locked, code 2 executes to lock (this) after B is locked, then code 1 requirements B, code 2 requirements A, at this time two requirements are in a standoff state of each other, the program is deadlock.


(2) Lock (typeof (MyType)) Issue:

Assume there are two public variables:

int A;float b;

Here's a look at the following code

Code Listing 3:

Lock (typeof (A))//typeof (a) is the System.type.Int type {//.... Lock (typeof (b)) {//...}}

The following code is also available:

Code Listing 4:

Lock (typeof (b))//typeof (b) is the System.type.Float type {//.... Lock (typeof (a)) {//...}}

If there are two processes at the same time into the above two code outer lock, System.type.Int and System.type.Float respectively locked, and immediately they need System.type.Float and System.type.Int, each other, each other, deadlocked, the program into the deadlock state!


(3) String problem:

Before elaborating on this, there is a knowledge that you must know that the string in C # is persisted by the common language runtime (CLR). This means that there is only one instance of any given string in the entire program, which is the same object that represents the text in all the threads of all running application domains. Therefore, whenever a lock is placed on a string that has the same content anywhere in the application process, all instances of that string in the application are locked.

The implication is that there are two classes with two strings, respectively:

Class a{string a= "abc"; string b= "Def";} Class c{string c= "abc"; string d= "Def";}

In fact A and C refer to the same string "abc", and B and D refer to the same string "Def"

Now if you have the following code in two classes

There is code 5 in Class A:

Lock (b)//b is "def" {//.... Lock (a)//a is "abc" {//...}}

There is code 6 in class B:

Lock (c)//c is "abc" {//.... Lock (d)//d is "def" {//...}}

Then code 5 and Code 6 have two thread execution results imaginable: "Def" and "ABC" are locked when two threads execute to the outer lock code. They then demanded "ABC" and "Def" at the same time in the internal lock, and at this time two strings were occupied by two processes, and the program was deadlocked! So MSDN says: Locking strings is especially dangerous! Best not to use!

MSDN concludes: The best practice is to define private objects to lock, or private shared object variables to protect data that is common to all instances.

In personal view, it is not absolutely safe, here is an example:

Suppose you have a class:

Class a{Private Object A=new object (), Private Object B=new object (), public void X () {  lock (A)  {    //.....
   
    lock (b)    {     //...}}  } public void Y () {  lock (b)  {    //...    .. Lock (a)    {     //...}    }}  
   

Now assume that there are two threads executing the function x () and Y () at the same time, the result is that private objects A and B are locked in the outer lock, and then two threads are inside and immediately demand B and a,a,b each other and require each other, and the program is deadlocked.

So it depends on the situation, but defining the private object to lock at least reduces the risk.

It is hoped that the application of lock in C # in this article will be helpful to everyone's C # programming.

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
Example of lock deadlock in C # tutorial

This address: http://www.paobuke.com/develop/c-develop/pbk23611.html






About C # programming how to get pictures in a resource file C # enumeration value increase property description (recommended) Simple analysis of the parameter problems encountered in C # calling external programs using process C # methods for invoking system APIs to specify shortcut keys
C # How to achieve Image sharpening C # method for calculating file MD5 checksum C # using delegates to analyze ASP. NET MVC 5 Paging tutorial using X.PAGEDLIST.MVC (PAGEDLIST.MVC)

Example of lock deadlock in C # tutorial

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.