I'm just looking in to the new .NET 4.0 features. With that, I'm attempting a simple calculation using Parallel.For
and a normal for(x;x;x)
loop.
However, I'm getting different results about 50% of the time.
long sum = 0;
Parallel.For(1, 10000, y =>
{
sum += y;
}
);
Console.WriteLine(sum.ToString());
sum = 0;
for (int y = 1; y < 10000; y++)
{
sum += y;
}
Console.WriteLine(sum.ToString());
My guess is that the threads are trying to update "sum" at the same time.
Is there an obvious way around it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…