views:

71

answers:

1

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

);

+3  A: 

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.

JSBangs
how can we add share variables while using "parallel.for". It is very easy to understand in this case one share variable in above code. But more then one in this case how to do ?There is one method that "locked" in C#. example:static readonly object stateLock = new object(); lock (stateLock) { variable1 variable2 }But i thought it is not good way to handle this problem.
Sharing variables with `Parallel.For` should be trivial--ordinary closures do that just fine. *Updating* variables is what's tricky, but the point is that if you're updating shared variables you really should think about something other than `Parallel.For`.
JSBangs
Also i think we can use any parameters on "type of parameter". So i used a massive type of int. But you are telling that the side-effects is ridiculous. Am i was thinking wrong ?
@user, I could answer your question better if you gave me a concrete example of what you're trying to do. Adding up a bunch of numbers in a loop is a poor usage of `Parallel.For`, and the syntax problems that you're having seem to reflect this.
JSBangs
Here is ...private int sum1=0,sum2=0;... for(int i=0;i<loop;i++) { { sum1 += (pop1[i].getRating()); sum2 += (pop2[i].getRating()); } }... that's it.