Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is += in python thread safe?

Tags:

python

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?

like image 344
truease.com Avatar asked Apr 28 '12 02:04

truease.com


2 Answers

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        
like image 180
Dan D. Avatar answered Oct 24 '22 20:10

Dan D.


+= is not threadsafe (source).

like image 33
Amber Avatar answered Oct 24 '22 20:10

Amber