C # lock details and implementation

Source: Internet
Author: User

The lock keyword can be used to ensure that the code block is executed without being interrupted by other threads. This is achieved by obtaining mutex locks for a given object during the code block operation.

Let's take a look at the execution process. The sample code is as follows:

The lock statement is used to obtain the mutex lock of a given object, execute a statement, and then release the lock.
Lock-statement :( lock statement :)
Lock (expression) embedded-statement (lock (expression) embedded statement)
The expression of the lock statement must represent a value of the reference type. The implicit packing conversion (section 6.1.5) is never performed for the expressions in the lock statement. Therefore, if the expression represents a value type value, it will lead to a compilation error.
The following lock statements
Lock (x )...
(X is a reference expression) is equivalent

System. threading. monitor. enter (x );
Try {
...
}
Finally {
System. threading. monitor. exit (x );
}

The difference is that in actual execution, x is calculated only once.
When a mutex lock is occupied, the Code executed in the same thread can still obtain and release the lock. However, the Code executed in other threads cannot be obtained before the lock is released.
The system. type object of a class can be conveniently used as a mutex lock for the static methods of the class. For example:

Class cache
{
Public static void add (object x ){
Lock (typeof (cache )){
...
}
}
Public static void remove (object x ){
Lock (typeof (cache )){
...
}
}
}

Assume that thread a is executed first, and thread B is a little slower. Thread a executes the lock statement to determine if obj has applied for a mutex lock,

The judgment is based on comparing object. referenceequals with the existing locks one by one (not confirmed here ).

Then, apply for a new mutex lock, and thread a enters the lock.

In this case, it is assumed that thread B is started, and thread a has not executed the code in the lock. Thread B executes the lock statement and checks the obj

After applying for a mutex lock, wait until thread a finishes executing the lock and releases the mutex lock. Thread B can apply for a new mutex lock and execute it.

The code in lock.

Next, let's talk about the lock object.

Why cannot I lock the value type, such as lock (1? Lock is essentially monitor. enter, and monitor. enter will pack the value type,

Each lock is a boxed object. The lock is similar to the syntax sugar of the compiler. Therefore, the compiler directly limits the lock value type.

Even if the compiler allows you to lock (1), but object. referenceequals (10 thousand) always returns false (because

Objects are different after each packing), that is to say, each time it is determined that no mutex lock is applied, so that at the same time, other threads can still

Access the code in it, and the synchronization effect cannot be reached. Similarly, lock (object) 1) does not work.

What about the lock ("xxx") string? The original words on msdn are:

Locking a string is especially dangerous because the string is "Temporarily" by the Common Language Runtime Library (clr ". This means that any given string in the entire program

There is only one instance, and the same object represents the text in all threads of all running application domains. Therefore, as long

If a lock is placed on a string with the same content at any location in the program process, all instances of the string in the application will be locked.

Generally, it is better to avoid locking the public type or locking an object instance that is not controlled by the application. For example, if the instance can be publicly accessed,

Lock (this) may cause problems because uncontrolled Code may also lock the object. This may lead to deadlocks, that is, two or more lines.

To release the same object. For the same reason, locking public data types (compared to objects) may also cause problems. And lock (this)

Only valid for the current object. If multiple objects cannot be synchronized.

Lock (typeof (class) is the same as locking a string and has a wide range.

Some system classes provide members dedicated for locking. For example, the array type provides syncroot. Many Collection types also provide syncroot.

For custom classes, private read-only static objects are recommended, for example:

Private static readonly object obj = new object ();

Why should I set it to read-only? In this case, if you change the obj value in the lock code segment, other threads will be unobstructed, because the mutex lock

Object. referenceequals returns false if the object is changed.

 

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.