What's an "atomic" operation (in a threaded context)?

Peter Hansen peter at engcorp.com
Wed Nov 12 17:49:10 EST 2003


Paul Moore wrote:
> 
> I can't find anything which spells this out in the manuals. I guess
> that, at some level, the answer is "a single bytecode operation", but
> I'm not sure that explains it for me.
> 
> This thought was triggered by a comment on the Python Cookbook site,
> which basically said that it was OK to do
>     tss = {}
>     ...
>     id = thread.get_ident()
>     tss[id] = {}
> 
> (where tss is a global) without a lock, because id is unique to the
> thread.
> 
> But couldn't this result in 2 threads allocating a new entry in tss at
> the same time, and so get tss in an inconsistent state?
> 
> I tried to understand this with the dis module:
> 
> >>> import dis
> >>> d = {}
> >>> def f(n):
> ...     d[n] = {}
> ...
> >>> dis.dis(f)
>   2           0 BUILD_MAP                0
>               3 LOAD_GLOBAL              0 (d)
>               6 LOAD_FAST                0 (n)
>               9 STORE_SUBSCR
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE

In a nutshell, your "single bytecode operation" theory is correct,
and each of the above lines represents a single bytecode.  Therefore
the only line which matters is STORE_SUBSCR (the actual assignment)
and it is atomic, so you can have any number of threads running but
no matter how they try, they won't be able to interrupt each other's
STORE_SUBSCR operations and the dictionary will stay in a consistent
state.

Much or most of the time, basic operation such as this on the standard
mutable primitive types (i.e. lists, dictionaries) are atomic/safe for
use in the way you wish to use them, without needing locks.

-Peter




More information about the Python-list mailing list