[Reprint] C # Use Interlocked for atomic operations,

Source: Internet
Author: User

[Reprint] C # Use Interlocked for atomic operations,

Source article: Wang Xu blog» C # Use Interlocked for atomic operations

What is an atomic operation?

Atom is intended to be "the smallest particle that cannot be further divided", while atomic operation is "one or a series of operations that cannot be interrupted ". When multiple threads operate on a variable in C # At the same time, we should use atomic operations to prevent the value obtained by multithreading from being the latest value.

For example, int result = 0;
Multi-thread A is executing result (0) + 1
Multithreading B executes result (0) + 1 at the same time

Then the finalresultThe result is1Or2That's hard to say. If two threads in the CPU calculate at the same time, the result is1Obviously, this result is not what we want. Of course you can uselockThe lock ensures the uniqueness of multi-thread execution, but its performance is far inferior to that of atomic operations.

Use Interlocked for atomic operations:

UseInterlockedClass can perform atomic operations on some data.lockThe lock is the same, but it is notlockThe atomic operation is based on the CPU itself, non-blocking, So comparedlockHigh efficiency.

The following uses the C # code to demonstrate atomic operations:

1 class Program 2 {3 // global variable 4 private static int _ result; 5 6 // Main method 7 static void Main (string [] args) 8 {9 // press Enter for several seconds after running, and use Interlocked. increment (ref _ result); different from _ result ++; 10 while (true) 11 {12 Task [] _ tasks = new Task [100]; 13 int I = 0; 14 15 for (I = 0; I <_ tasks. length; I ++) 16 {17 _ tasks [I] = Task. factory. startNew (num) => 18 {19 var taskid = (int) num; 20 Work (taskid); 21}, I); 22} 23 24 Task. waitAll (_ tasks); 25 Console. writeLine (_ result); 26 27 Console. readKey (); 28} 29} 30 31 // thread call Method 32 private static void Work (int TaskID) 33 {34 for (int I = 0; I <10; I ++) 35 {36 // _ result ++; 37 Interlocked. increment (ref _ result); 38} 39} 40}

Run the above Code to comment out the last two lines of code respectively._result++;AndInterlocked.Increment(ref _result);And then press Enter to keep running for several seconds. You can see the difference between the two.

So farInterlockedFunction, download the sample source code in this article: Interlocked_Sample.

Other Instructions on atomic operations: Execute the value assignment command on a 32-bit CPU. the maximum data transmission width is 4 bytes. Therefore, as long as the read and write operations are less than 4 bytes, 32-bit CPUs are atomic operations. Sobool,intThese types of operations are atomic operations. WhileInterlockedThe provided atomic operation method is completed by functional CPU command encapsulation at the underlying layer.

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.