Implementing thread synchronization with interlocked

Source: Internet
Author: User

There are many ways to thread synchronization, and if you are just sharing integer data, you can use interlocked for synchronization.

Here is an example of how to use interlocked for synchronization.

I. Illustrative examples
1             int 0 ; 2             Parallel.For (110001, i =3            {4                 1; 5             }); 6             " Results: " + sum;

Looking at the code above, after 10,000 parallel loops, the last value of the sum variable is expected to be 10000. However, due to resource conflicts, the final value of sum is not deterministic, and most cases are less than 10000.

Second, the solution

There are a number of ways to synchronize, such as using a single object to synchronize. However, here we use interlocked to synchronize, the code is as follows:

1             int 0 ; 2             Parallel.For (110001, i =3            {4                 Interlocked.Increment (ref  sum); 5             }); 6             " Results: " + sum;

Run the sum value of 10000 for each run.

Implementing thread synchronization with interlocked

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.