oshaiken
oshaiken

Reputation: 2650

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

Upvotes: -1

Views: 158

Answers (2)

zanseb
zanseb

Reputation: 1425

Python's built-in structures are thread safe for single operations. The GIL (global interpreter lock) takes care of that. But it is mostly difficult to see where a statement becomes more operations.

Adding a lock will give you peace of mind:

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122042

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.

Upvotes: 3

Related Questions