In parallel.for share value more then one.
Posted
by user347918
on Stack Overflow
See other posts from Stack Overflow
or by user347918
Published on 2010-05-25T17:43:02Z
Indexed on
2010/05/25
17:51 UTC
Read the original article
Hit count: 211
c#
|parallel-processing
Here is problem.
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 sum1 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]));
© Stack Overflow or respective owner