Parallel.For(): Different results for simple addition
Posted
by TSS
on Stack Overflow
See other posts from Stack Overflow
or by TSS
Published on 2010-05-05T14:37:54Z
Indexed on
2010/05/05
14:48 UTC
Read the original article
Hit count: 114
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 (no code change).
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());
Surely I'm missing something simple or do not completely understand the concept. My guess is that the threads are trying to update "sum" at the same time. If so, is there an obvious way around it?
© Stack Overflow or respective owner