Is x+=1 threadsafe? No it isn't...

Friday 09 May 2008, 01:25:00 | python

A question that popped up on comp.lang.python the other day:

I still can not believe that +=1 is not a thread safe operation. Any clue?

Yes, indeed, the statement

x+=1

is not thread-safe (or atomic, as you wish). Why the hell is that?

Well, the statement:

x+=1

is equivalent to:

x = x.__iadd__(1)

i.e. a function call followed by an assignment. The function call may execute atomicly, but the combination of this with the second operation (rebinding of the new integer object to x) isn't atomic.

So if we want to use simple counters across threads, they also need to be synchronised by proper lock objects.

While I'm not 100% sure about var++ in Java, I'm pretty sure that in C/C++ the statement is compiled into a single atomic machine instruction (such as INC). However in a multiprocessor / shared memory environment that could still result in wrong values. Better to always use a locking mechanism, even for seemingly simple things as incrementing a single counter...