Friday 8 March 2013

No, the ++ operators are not thread safe

G'day:
My lunch break is running out (by about -10min so far ;-), so this will be quick.

In my last article I got bitten on the bum by weird behaviour of the prefix increment operator (ie: ++myVar), in that two simultaneous calls to it would cause the increment to skip.

Doing some research (basically asking my colleague Simon) , I discovered that - no - these operators are not thread safe. This is good to know.


I googled about, and found this good explanation on Stackoverflow. Basically, the ++ operation can be summarised like this:
  1. get the current value of the variable;
  2. increment that value;
  3. set the variable to have that value.
So now think about two threads running this "code":

++myVar // currently has the value 42

T1 gets the value of myVar (42)
T2 gets the value of myVar (42)
T1 increments the value (43)
T2 increments the value (43)
T1 sets myVar to have the incremented value (43)
T2 sets myVar to have the incremented value (43)

So ++myVar has been hit twice, but its value has only been incremented the once.

Like I said: good to know. Cheers for the nudge there, Simon.

And that's it!

--
Adam