Do I need to syncronize thread access to an int

Posted by Martin Harris on Stack Overflow See other posts from Stack Overflow or by Martin Harris
Published on 2009-07-06T15:57:31Z Indexed on 2010/03/15 0:19 UTC
Read the original article Hit count: 192

Filed under:
|
|
|

I've just written a method that is called by multiple threads simultaneously and I need to keep track of when all the threads have completed, the code uses this pattern:

private void RunReport()
{
   _reportsRunning++;

   try
   {
       //code to run the report
   }
   finally
   {
       _reportsRunning--;
   }
}

This is the only place within the code that _reportsRunning's value is changed, and the method takes about a second to run.

Occasionally when I have more than six or so threads running reports together the final result for _reportsRunning can get down to -1, if I wrap the calls to _runningReports++ and _runningReports-- in a lock then the behaviour appears to be correct and consistant.

So, to the question: When I was learning multithreading in C++ I was taught that you didn't need to synchronize calls to increment and decrement operations because they were always one assembly instruction and therefore it was impossible for the thread to be switched out mid-call. Was I taught correctly, and if so how come that doesn't hold true for C#?

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading