Thread-safety of dict
Raymond Hettinger
python at rcn.com
Sat Jun 2 01:55:45 EDT 2007
On May 31, 9:12 pm, "Adam Olsen" <rha... at gmail.com> wrote:
> It seems to be a commonly held belief that basic dict operations (get,
> set, del) are atomic.
They are atomic so long as the key does not have a custom __hash__,
__eq__, or __cmp__ method which can trigger arbitrary Python code.
With strings, ints, floats, or tuples of those, the get/set/del step
is atomic (i.e. executed in a single Python opcode).
>>> from dis import dis
>>> dis(compile('del d[k]', 'example', 'exec'))
1 0 LOAD_NAME 0 (d)
3 LOAD_NAME 1 (k)
6 DELETE_SUBSCR
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
The DELETE_SUBSCR step completes the whole action in a single opcode
(unless the object has a custom hash or equality test). Of course,
there is a possibility of a thread switch between the LOAD_NAME and
the DELETE_SUBSCR (in which case another thread could have added or
removed that key).
Raymond
More information about the Python-list
mailing list