is +=1 thread safe

Hrvoje Niksic hniksic at xemacs.org
Fri May 2 04:24:48 EDT 2008


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:

> AlFire <spamgrinder.trylater at ggmail.com> writes:
>> But I still can not believe that +=1 is not a thread safe operation.
>
> In CPython I believe it is thread safe, because of the global
> interpreter lock.  Thread switches can happen only between bytecode
> executions, not in the middle of a bytecode, even though executing a
> bytecode can take several machine instructions.

It's safe when writing extensions in C (because of the GIL), but not
when writing Python code.  Python switches threads after a number of
bytecode instructions, so Python code behaves somewhat like C
multithreaded code on a single CPU -- although there is no true
parallelism, you still have context switches at arbitrary places to
worry about, and still need locks because of them.  Since the +=
operator is not compiled into a single bytecode instruction, it needs
the lock.  x+=1 gets compiled into the following bytecode:

  3           0 LOAD_GLOBAL              0 (x)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD
              7 STORE_GLOBAL             0 (x)

If two threads execute that code simultaneously, a thread switch could
easily occur some time between LOAD_GLOBAL and STORE_GLOBAL, causing
the variable to be incremented by 1 instead of by 2.



More information about the Python-list mailing list