8
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

结果是 999 在我的测试中,我似乎 += 线程安全我的问题是:+= 真的是线程安全的吗?

4

2 回答 2

19

不,它不是线程安全的,因为该操作x += 1需要 4 个操作码,如下所示:

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

选自:

>>> 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        
于 2012-04-28T02:13:41.310 回答
10

+= is not threadsafe (source).

于 2012-04-28T02:13:15.860 回答