I have a foreach loop that I am parallelizing and I noticed something odd. The code looks like
double sum = 0.0;
Parallel.ForEach(myCollection, arg =>
{
sum += ComplicatedFunction(arg);
});
// Use sum variable below
When I use a regular foreach loop I get different results. There may be something deeper down inside the ComplicatedFunction but it is possible that the sum variable is being unexpectantly affected by the parallelization?
Yes.
Access to a
doubleis not atomic and thesum += ...operation is never thread-safe, not even for types that are atomic. So you have multiple race conditions and the result is unpredictable.You could use something like:
or, in a shorter notation