Category Archives: Parallel Programming

C# Parallel Programming – Increment variable safely across multiple threads

On one of my recent projects, I utilized a bit of parallel programming via the C# Parallel.ForEach construct.  Within the foreach loop, I needed to log what current step in the process I was on, like so Step 1 of n.  So this means we need some sort of variable (let’s call it “x”) that can be incremented to indicate the step number.

Now, we could simply try to increment the variable (as seen below), however, the problem here is that you can have two threads operating concurrently on separate processors, but accessing the same variable.  This may cause  process on thread 1 to increment variable “x” from 0 to 1, but because the process is non atomic (other actions can be performed on the value at the same time), process on thread 2 can at the same time access the value of variable “x”, but still read the value as 0 as it hasn’t been saved yet.


int index = 0;
Parallel.ForEach(databaseNameList, (dbName) =>
{
var currIndex = index++;
Log(String.Format("Step {0} of {1}", currIndex, databasenameList.Count));
});

To get around this, we’ll need something that can safely change the value of a shared variable from multiple threads.  This can be accomplished using the lock statement, and you can find an example here.  However, for simpler and faster code, we will utilize the C# Interlocked class.  The Interlocked class has numerous members we can call, but in our case we are particularly interested in the Increment method.  What makes it great is that it performs the increment task in one atomic (meaning no other action can be performed on the value at the same time) operation.  So instead of the above piece of code, it changes slightly to the below code sample.


int index = 0;
Parallel.ForEach(databaseNameList, (dbName) =>
{
var currIndex = Interlocked.Increment(ref index);
Log(String.Format("Step {0} of {1}", currIndex, databasenameList.Count));
});

This is a post I’ve held on to and wanted to post for a long while now, so I know it may not be new information, but still hope this little tidbit is useful to someone else.

Tagged , , ,
%d bloggers like this: