is += in python thread safe?

前端 未结 2 1469
长发绾君心
长发绾君心 2021-02-09 01:31
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 glo         


        
2条回答
  •  野性不改
    2021-02-09 02:18

    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        
    

提交回复
热议问题