atomic operations in presence of multithreading

Peter Hansen peter at engcorp.com
Tue Jul 27 17:03:14 EDT 2004


Dave Brueck wrote:

> Glenn Kasten wrote:
> 
>> I am wondering which operations in Python
>> are guaranteed to be atomic in the presence
>> of multi-threading. In particular, are assignment
>> and reading of a dictionary entry atomic?
> 
 > [...]
> Basically: multiple threads can't corrupt the interpreter's internals 
> (but a buggy C extension could).

The "dis" module can be helpful in analyzing such things, sometimes.
Realizing that the GIL ensures that individual bytecodes are
executed atomically ("boom!"), anything that shows up as a
separate bytecode instruction is basically thread-safe:

 >>> def func():
...   v = dictionary[key]
...
 >>> def func2():
...   dictionary[key] = new_value2
...
 >>> dis.dis(func)
   2           0 LOAD_GLOBAL              0 (dictionary)
               3 LOAD_GLOBAL              1 (key)
               6 BINARY_SUBSCR
               7 STORE_FAST               0 (v)
              10 LOAD_CONST               0 (None)
              13 RETURN_VALUE
 >>> dis.dis(func2)
   2           0 LOAD_GLOBAL              0 (new_value2)
               3 LOAD_GLOBAL              1 (dictionary)
               6 LOAD_GLOBAL              2 (key)
               9 STORE_SUBSCR
              10 LOAD_CONST               0 (None)
              13 RETURN_VALUE

The key instructions in the above are the dictionary lookup,
which is merely "BINARY_SUBSCR" in func(), and the dictionary
assignment, which is "STORE_SUBSCR" in func2().  If func
and func2 were in separate threads, either the lookup or
the store executes first, then the other, but they cannot
both be executing at the same time.

-Peter



More information about the Python-list mailing list