Techniques for atomic manipulation using interlocked in C #

Source: Internet
Author: User
What is atomic manipulation?

Atom (Atom) is intended to be "the smallest particle that cannot be further divided", while atomic manipulation (atomic operation) means "one or a series of operations that cannot be interrupted". When there are multiple threads working on a variable in C #, we should use atomic operations to prevent multithreading from fetching values that are not up to date.

For example: int result = 0;

Multithreaded A is executing result (0) +1

Multithreading b Simultaneous execution result (0) +1

So the final result is 1 or 2, which is hard to say. If 2 threads compute at the same time in the CPU, then the result is 1, obviously this is not what we want. Of course you can use lock lock to ensure the uniqueness of multi-threaded execution, but its performance is far less than the way atomic operations.

Use Interlocked for atomic operations:

Use. NET provides the Interlocked class can be atomic operation of some data, it looks like a lock lock, but it is not lock lock, its atomic operation is based on the CPU itself, non-blocking, so it is more efficient than lock.

The following is a demonstration of atomic operations using C # code:

Class program{//global variable private static int _result;//main method static void Main (string[] args) {//Run and hold the ENTER key for several seconds,  Contrast using interlocked.increment (ref _result); differs from _result++ while (true) {task[] _tasks = new Task[100];int i = 0;for (i = 0; i < _tasks. Length; i++) {_tasks[i] = Task.Factory.StartNew ((num) =>{var taskid = (int) num; Work (TaskID);}, i);} Task.waitall (_tasks); Console.WriteLine (_result); Console.readkey ();}} The thread calls the method private static void work (int TaskID) {for (int i = 0; i <; i++) {//_result++;interlocked. Increment (ref _result);}}}


The above code runs separately comments the last two lines of code _result++, and Interlocked.Increment (ref _result), the line is run again, after running, press and hold the ENTER key to run for a few seconds, you can see the difference between the differences.

At this point, it reflects the role of interlocked, the sample source code download: Interlocked_sample.

Additional instructions on atomic operations: Perform an assignment instruction on a 32-bit CPU, the maximum width of the data transfer is 4 bytes. So as long as the read-write operation is under 4 bytes, the 32-bit CPUs are atomic operations. so bool, int these types of operations themselves are atomic operations. The atomic operation method provided by interlocked is done by the functional CPU instruction encapsulation at the bottom.

The above is a small part of the introduction of the C # in the use of interlocked atomic operation of the skills, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. For more related articles, please follow topic.alibabacloud.com (www.php.cn)!

  • 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.