How to Increment/Decrement A Variable In A Thread Safe Manner

December 31, 2008

Sometimes it will be necessary to increment or decrement a variable in a atomic manner so that no other thread can affect it while being incremented/decremented. The complex mutexes and critical sections can do the trick. Still, there is a single line API which does the same and it is

LONG InterlockedIncrement(LONG volatile* Addend)

(InterlockedDecrement for decrementing the value).

For example,

LONG myNo = 10;
LONG returnValue = InterlockedIncrement(&myNo);

will make

myNO = 11 and returnValue = 11.