开发者

In parallel.for share value more then one

Here is probl开发者_如何学Goem.

long sum = 0;
Parallel.For(1, 10000, y => { sum1 += y;} );

Solution is ..

Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
{
    subtotal += result[i];
    return subtotal;
},
(x) => Interlocked.Add(ref sum, x)
);

if there are two parameters in this code. For example

long sum1 = 0; long sum2 = 0;
Parallel.For(1, 10000, y => { sum1 += y; sum2=sum1*y; } );

what will we do ? i am guessing that have to use array !

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

);


I'm not sure that I can solve your problem, because I don't really know what it is. But there's a good reason that Parallel.For doesn't easily support accumulators like this: because it's ridiculous to attempt to parallelize a simple operation with side-effects.

Parallel.For is for parallelizing relatively expensive operations that don't have side effects that depend on each other. A regular for loop (or Accumulate) is the right thing to do here.


See Microsoft's sample on thread local variables, for information on updating globals in a parallel for.


Just expand expression such way:

(x) => { Interlocked.Add(ref sum1, x[0]); Interlocked.Add(ref sum2, x[1]); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜