Different summation results with Parallel.ForEach

前端 未结 4 750
梦谈多话
梦谈多话 2020-12-15 18:31

I have a foreach loop that I am parallelizing and I noticed something odd. The code looks like

double sum = 0.0;

Parallel.ForEach(myCollection         


        
4条回答
  •  执念已碎
    2020-12-15 18:58

    it is possible that the sum variable is being unexpectantly affected by the parallelization?

    Yes.
    Access to a double is not atomic and the sum += ... operation is never thread-safe, not even for types that are atomic. So you have multiple race conditions and the result is unpredictable.

    You could use something like:

    double sum = myCollection.AsParallel().Sum(arg => ComplicatedFunction(arg));
    

    or, in a shorter notation

    double sum = myCollection.AsParallel().Sum(ComplicatedFunction);
    

提交回复
热议问题