globalnum = 0
n = 1
class T( threading.Thread ):
  def run( self ):
    global globalnum
    globalnum += n
for _ in xrange( 0, 999 ):
  t = T()
  t.start()
print globalnum
the result is 999 In my test i seems += thread safe My question is: is += really thread safe?
No, it isn't thread-safe as the operation x += 1 takes 4 opcodes as shown below:
  4           0 LOAD_GLOBAL              0 (x)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD         
              7 STORE_GLOBAL             0 (x)
selected out of:
>>> import dis
>>> def test():
...     global x
...     x += 1
...     
... 
>>> dis.disassemble(test.func_code)
  4           0 LOAD_GLOBAL              0 (x)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD         
              7 STORE_GLOBAL             0 (x)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE        
                        += is not threadsafe (source).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With