这是问题。
long sum = 0;
Parallel.For(1, 10000, y => { sum1 += y;} );
解决方案是......
Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
{
subtotal += result[i];
return subtotal;
},
(x) => Interlocked.Add(ref sum, x)
);
如果此代码中有两个参数。例如
long sum1 = 0; long sum2 = 0;
Parallel.For(1, 10000, y => { sum1 += y; sum2=sum1*y; } );
我们会怎么做?我猜这必须使用数组!
int[] s=new int[2];
Parallel.For<int[]>(0, result.Count, () => s, (i, loop, subtotal) =>
{
subtotal[0] += result[i];
subtotal[1] -= result[i];
return subtotal;
},
(x) => Interlocked.Add(ref sum1, x[0])
//but how about sum2 i tried several way but it doesn't work.
//for example like that
//(x[0])=> Interlocked.Add (ref sum1, x[0])
//(x[1])=> Interlocked.Add (ref sum2, x[1]));
);
答案 0 :(得分:4)
我不确定我能解决你的问题,因为我真的不知道它是什么。但是有一个很好的理由Parallel.For
不容易支持这样的累加器:因为尝试并行化具有副作用的简单操作是荒谬的。
Parallel.For
用于并行化相对昂贵的操作,这些操作没有相互依赖的副作用。常规for循环(或Accumulate
)是正确的做法。
答案 1 :(得分:0)
有关以并行方式更新全局变量的信息,请参阅thread local variables上的Microsoft示例。
答案 2 :(得分:0)
只需扩展表达方式:
(x) => { Interlocked.Add(ref sum1, x[0]); Interlocked.Add(ref sum2, x[1]); }