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?
Accessing shared state will most likely not produce the desired result. Simple example:
change this to
and you’ll see
sumwill have some random value because multiple threads are reading/writingsum.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.