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
+=
is not threadsafe (source).
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