O'Reilly logo

C# Multithreaded and Parallel Programming by Rodney Ringler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using thread-local variables in parallel loops

Once you are comfortable using parallel loops, stopping them, and performing exception handling with them, let's talk about how we can use thread-local variables to better coordinate results. If we want to sum the results of all the iterations of a parallel loop, how would we do that?

From what we have learned so far, we would create a class variable before the loop and access it by each iteration of the loop using a lock statement so that it remains thread-safe. This takes overhead and coordination time. To improve performance, we can implement our parallel loop using a thread-local variable.

The Parallel.For and Parallel.ForEach loops both have overloads that implement a thread-local variable. What ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required