C # interlocked class that provides atomic operations for Multithreaded Variables

Source: Internet
Author: User

Multithreading is often used in recent work, but the problem of multi-threaded shared variables needs to be solved. Fortunately,. NET provides the interlocked class for us, but Microsoft provides atomic operation classes for variables shared by multiple threads. One of the frequently used methods is interlocked. increment () and interlocked. decrement ().

The following describes the two methods on msdn:

Increment and
The decrement method increments or decreases the variable and stores the result value in a single operation.
On most computers, adding a variable is not an atomic operation. You need to perform the following steps:

  1. Load the values in instance variables into registers.

  2. Increase or decrease the value.

  3. Store this value in instance variables.

If you do not use
Increment and
Decrement, the thread will be preemptible after the first two steps are executed.
Then, the other thread executes all three steps.
When the first thread starts execution again, it overwrites the value in the instance variable, resulting in loss of the result of the increase or decrease operation in the second thread.

For more details about the interlocked class, refer to the introduction on msdn:

Bytes.

In fact, we have another way to lock variables or files in multiple threads, as shown below:

Lock ()
{

// Do something...

}

In general, do not lock the public type; otherwise, the instance will be out of the control scope of the Code. Common structures such as lock (this), lock (typeof (mytype), and lock ("mylock") violate this rule: if an instance can be accessed by the public, C # Lock this problem will occur. If mytype can be accessed by the public, the lock (typeof (mytype) problem will occur. Any other code that uses the same string in the process will share the same lock, so the lock ("mylock") problem occurs. Let's take a look at the issue of C # Lock this: if there is a class class1, this class has a method to implement mutual exclusion using lock (this:

 
 
  1. publicvoidMethod2()  
  2. {  
  3. lock(this)  
  4. {  
  5. System.Windows.Forms.MessageBox.Show("Method2End");  
  6. }  

In the same class1 instance, The method2 can be mutually exclusive. However, if two class1 instances run method2 respectively, there is no mutex effect. Because the lock here only locks the current instance object.

Lock (typeof (mytype) locks a wider range of objects, because all instances of a class have only one type object (this object is the return result of typeof), lock it, it locks all instances of this object. Microsoft recommends that you do not use lock (typeof (mytype) because locking a type object is a very slow process, other threads in the class, or even other programs running in the same application domain, can access this type of object. Therefore, they may be used to lock the type object instead of you, it completely blocks your execution and causes your own code to be suspended.

Locking a string is even more amazing. As long as the string content is the same, it can cause the program to be suspended. The reason is that in. net, the string will be temporarily stored. If the two variables have the same string content,. NET will allocate the temporary String object to the variable. So if both of them are using lock ("My lock"), they actually lock the same object. At this point, Microsoft provides a recommended lock usage: locking a private static member variable.

. Net in some collection classes (such as arraylist, hashtable, queue, stack) has provided a Lock Object syncroot, and used the reflector tool to view the syncroot attribute code. In the array, this attribute has only one sentence: return this, which is the same as the current instance of lock array. Syncroot in arraylist is different.

 
 
  1. get  
  2. {  
  3. if(this._syncRoot==null)  
  4. {  
  5. Interlocked.CompareExchange(refthis._syncRoot,newobject(),null);  
  6. }  
  7. returnthis._syncRoot;

It is important to note that enumeration of a set from start to end is not a thread-safe process. Even if a set has been synchronized, other threads can modify the set, which causes an exception in the number of enumerations. To ensure thread security during enumeration, you can lock the set throughout the enumeration process:

 
 
  1. QueuemyCollection=newQueue();  
  2. lock(myCollection.SyncRoot){  
  3. foreach(ObjectiteminmyCollection){  
  4. //Insertyourcodehere.  
  5. }  
  6. }


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.