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

查看:12
本文介绍了Parallel.ForEach 的不同求和结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在并行化的 foreach 循环,我注意到一些奇怪的事情.代码看起来像

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

当我使用常规的 foreach 循环时,我得到了不同的结果.ComplicatedFunction 内部可能有一些更深的东西,但有可能 sum 变量意外地受到并行化的影响?

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?

推荐答案

sum 变量是否有可能受到并行化的意外影响?

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

是的.
double 的访问不是原子的,并且 sum += ... 操作永远不是线程安全的,即使对于原子类型也是如此.所以你有多个竞争条件,结果是不可预测的.

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));

或者,用更短的符号

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

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

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