Thread Synchronization (i)

Source: Internet
Author: User

Solution : A resource that only allows one thread at a time, and the other threads can only wait. Until the resource is freed.

problem Abstraction : When a resource may be read and modified by multiple threads at the same time, the state of the resource becomes unpredictable.

thread Synchronization Scenarios : Volatile, lock, interlocked, Moniter, SpinLock, Readwritelockslim, Mutex

Scheme features : except the owner, others wait unconditionally; first come, first served.

differences between scenarios: These scenarios can be divided into three types from their respective implementations: User-mode constructs, kernel-mode constructs, and mixed-mode constructs.

User-mode constructs should be used as much as possible, and they are significantly faster than kernel-mode constructs. This is because they use special CPU instructions to coordinate threads. This means that coordination occurs in hardware (so it's so fast). They have one drawback: only the Windows operating system kernel can stop a thread from running (to avoid wasting CPU time). Therefore, a thread that wants to acquire a resource but is temporarily unavailable will continue to run in user mode. This can waste a lot of CPU time.

Kernel-mode constructs are provided by the Windows operating system itself. Therefore, they require you to invoke functions implemented in the operating system kernel in the application's thread. Switching threads from user mode to kernel mode (or vice versa) incurs a significant performance penalty, which is why you should avoid using kernel-mode constructs. Then, they have an important advantage: when a thread uses a kernel-mode construct to get a resource owned by another thread, Windows blocks the thread so that it no longer wastes CPU time . Then, when the resource becomes available, Windows resumes the thread and allows it to access the resource.

----"CLR via C # (3rd edition)" P706

First, the volatile keyword

Volatile is the simplest method of synchronization, and of course, it's a price to pay. It can only be synchronized at the variable level, the meaning of volatile is to tell the processor, do not put me into the working memory, please directly in main memory operation me. ("www.bitsCN.com") therefore, when multithreading accesses the variable at the same time, it will manipulate the main memory directly and do the variable sharing in essence.

The number of types that can be identified as volatile must be the following: (excerpt from MSDN)

    • Any reference type.
    • Any pointer type (under an unsafe context).
    • The types sbyte, Byte, short, ushort, int, uint, char, float, bool.
    • An enum type with a enum base type of Byte, SByte, short, ushort, int, or UINT.

Such as:

public class a{private volatile int _i;public int I{get {return _i;} set {_i = value;}}}

However, volatile does not achieve true synchronization because its operating level is only at the variable level, not at the atomic level. If it is in a single processor system, there is no problem, the variable in main memory has no chance to be modified by others, because there is only one processor, which is called Processor self-consistency. However, in a multiprocessor system, there may be a problem. Each processor has its own data cach, and the updated data is not necessarily immediately written back to main memory. So it can be a different step, but it's very difficult to happen because the Cach read and write very fast, flush frequency is also very high, only when the stress test can occur, and the probability is very very small.

Second, lock keyword

Lock is a simple and easy way to synchronize threads by acquiring mutexes for a given object. It ensures that when a thread is in a critical section of code, another thread does not come in, it waits until the thread object is freed, that is, the thread is out of the critical section. Usage:

public void Function () {Object lockThis = new Object (); Lock (LockThis) {//Access thread-sensitive resources.}}

  The parameter of lock must be based on the reference type of the object, not the basic type like bool,int, so it is not synchronous at all, because the parameters of lock is the object, if the incoming int, it is bound to take place boxing operation, so each lock will be a new different object. It is best to avoid using the public type or an object instance that is not controlled by the program because it is likely to cause deadlocks. In particular, do not use a string as a parameter to lock because the string is "persisted" by the CLR, meaning that there is only one instance of the string given in the entire application, so it is more likely to cause deadlocks. It is recommended that you use a private or protected member that is not "persisted" as a parameter. In fact, some classes have already provided dedicated members to be locked, such as the array type provides SyncRoot, and many other collection types also provide syncroot.

Therefore, use lock should pay attention to the following points:

1. If the instance of a class is public, it is best not to lock (this). Because the person who uses your class may not know that you are using lock, and if he has a new instance, and locks the instance, it can easily cause a deadlock.

2. If MyType is public, do not lock (typeof (MyType))

3. Never lock a string

Third, System.Threading.Interlocked

For simple operations of integer data types, you can use the members of the Interlocked class to implement thread synchronization, which exists in the System.Threading namespace. The Interlocked class has the following methods: Increment, Decrement, Exchange, and CompareExchange. Using increment and decrement guarantees that an integer can be added and reduced to an atomic operation. The Exchange method automatically swaps the value of the specified variable. The CompareExchange method combines two actions: comparing two values and storing the third value in one of the variables based on the result of the comparison. The comparison and interchange operations are also performed by atomic operations. Such as:

int i = 0; System.Threading.Interlocked.Increment (ref i); Console.WriteLine (i); System.Threading.Interlocked.Decrement (ref i); Console.WriteLine (i); System.Threading.Interlocked.Exchange (ref i, 100); Console.WriteLine (i); System.Threading.Interlocked.CompareExchange (ref I, 10, 100);

  

Thread Synchronization (i)

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.