不同的求和结果与Parallel.ForEach [英] Different summation results with Parallel.ForEach
问题描述
我有我并行化的foreach
循环,我发现了一些奇怪的。代码如下
双总和= 0.0;
Parallel.ForEach(MyCollection的,ARG = GT;
{
总和+ = ComplicatedFunction(ARG);
});
//使用金额低于变量
当我使用普通的的foreach
循环我得到不同的结果。可能有更深层次的东西倒在 ComplicatedFunction
,但它是可能的之
变量被unexpectantly受并行
它是可能的和变量被unexpectantly受并行
块引用>
是的,到结果
访问一个双击
不是原子和之和+ = ...
操作从来都不是线程安全的,即使是原子类型没有。所以,你有多个竞争条件,结果是不可预知的。
您可以使用类似:
双总和= MyCollection的。 。进行AsParallel()总和(ARG => ComplicatedFunction(ARG));
,或在较短的符号
双总和= myCollection.AsParallel()总和(ComplicatedFunction)。
I have a
foreach
loop that I am parallelizing and I noticed something odd. The code looks likedouble sum = 0.0; Parallel.ForEach(myCollection, arg => { sum += ComplicatedFunction(arg); }); // Use sum variable below
When I use a regular
foreach
loop I get different results. There may be something deeper down inside theComplicatedFunction
but it is possible that thesum
variable is being unexpectantly affected by the parallelization?解决方案it is possible that the sum variable is being unexpectantly affected by the parallelization?
Yes.
Access to adouble
is not atomic and thesum += ...
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);
这篇关于不同的求和结果与Parallel.ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!