不同的求和结果与Parallel.ForEach [英] Different summation results with Parallel.ForEach

查看:136
本文介绍了不同的求和结果与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 like

double 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 the ComplicatedFunction but it is possible that the sum 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 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);

这篇关于不同的求和结果与Parallel.ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆