pythonmultithreadingpython-2.7dictionaryaugmented-assignment

Is this code thread-safe in python 2.7?


Should I use atomic counter with Locking or can I use this?

 def somefunc(someparam):
     if someparam:
        dic['key'] +=1

Solution

  • No, your code is not threadsafe, because using an += augmented assignment on a dictionary value takes 3 opcodes to execute:

    >>> dis.dis(compile("dic['key'] += 1", '', 'exec'))
      1           0 LOAD_NAME                0 (dic)
                  3 LOAD_CONST               0 ('key')
                  6 DUP_TOPX                 2
                  9 BINARY_SUBSCR
                 10 LOAD_CONST               1 (1)
                 13 INPLACE_ADD
                 14 ROT_THREE
                 15 STORE_SUBSCR
                 16 LOAD_CONST               2 (None)
                 19 RETURN_VALUE
    

    The opcode at position 9, BINARY_SUBSCR retrieves the current value from the dictionary. Anywhere between opcodes 9 and 15 (where STORE_SUBSCR puts the value back in), a thread-switch could take place and a different thread could have updated the dictionary.