Friday, 9 August 2013

Parallel.for causes different results (C#)

Parallel.for causes different results (C#)

I am currently trying to improve a C# project I am working on.
Specifically, my goal is to parallelize some operations to reduce
processing time. I am starting with small snippets just to get the hang of
it. The following code (not parallel) works correctly (as expected)
for (int i = 0; i < M; i++)
{
double d;
try
{
d = Double.Parse(lData[i]);
}
catch (Exception)
{
throw new Exception("Wrong formatting on data number " + (i + 1)
+ " on line " + (lCount + 1));
}
sg[lCount % M][i] = d;
}
By using the following (parallel) code I would expect to obtain the exact
same results, but that is not the case.
Parallel.For(0, M, i =>
{
double d;
try
{
d = Double.Parse(lData[i]);
}
catch (Exception)
{
throw new Exception("Wrong formatting on data number " + (i + 1) +
" on line " + (lCount + 1));
}
sg[lCount % M][i] = d;
});
The part of the program these snippets are from reads data from a file,
one line at a time. Each line is a sequence of comma-separated double
precision numbers, that I put in the vector lData[] using String.Split().
Every M lines, the data sequence starts over with a new data frame (hence
the % M in the element index when i assign the values).
It is my understanding (clearly wrong) that by putting the code from the
(serial) for-loop in the third parameter of Parallel.For I parallelize its
execution. This shouldn't change the results. Is the problem in the fact
that the threads are all accessing to lCount and M? Should I make
thread-local copies?
Thanks.
(since I'm new I am not allowed to create the Parallel.For tag)

No comments:

Post a Comment