Changing foreach loops to Parallel.ForEach and weird bugs
c#
Solution
Accessing shared state will most likely not produce the desired result. Simple example:
int sum = 0;
for (int i = 0; i < 1000000; i++)
{
sum++;
}
change this to
Parallel.For(0, 1000000, i => { sum++; });
and you'll see `sum` will have some random value because multiple threads are reading/writing `sum`.
If you lock around the update, you'll solve the problem, but you'll essentially turn the operation into a sequential operation again.
You need to make sure that whatever happens in the loop is safe.
Microsoft Patterns and Practices did a book that explains all this and more. You should check that out before you simply change the code to use parallel loops.
Problem
I have several loops that I wrote using the traditional syntax ``` foreach(x in xs) {....} ``` Some of these loops are pretty intensive in terms of computation and I just changed them using the parallel syntax like this: ``` Parallel.ForEach(x, xs => {...}); ``` I see a major increase in performance!! Now my question is this: Am I introducing bugs using parallel multithreading? I read that thread safety is complex and can create weird bugs; what should I be concerned about?