Parallel.For(): Update variable outside of loop

前端 未结 7 2089
面向向阳花
面向向阳花 2020-11-29 22:20

I\'m just looking in to the new .NET 4.0 features. With that, I\'m attempting a simple calculation using Parallel.For and a normal for(x;x;x) loop.

7条回答
  •  悲&欢浪女
    2020-11-29 22:59

    sum += y; is actually sum = sum + y;. You are getting incorrect results because of the following race condition:

    1. Thread1 reads sum
    2. Thread2 reads sum
    3. Thread1 calculates sum+y1, and stores the result in sum
    4. Thread2 calculates sum+y2, and stores the result in sum

    sum is now equal to sum+y2, instead of sum+y1+y2.

提交回复
热议问题