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

Paul Moore pf_moore at yahoo.co.uk
Wed Nov 12 17:41:09 EST 2003


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

But I'm not sure to make of that.

Can anyone clarify this for me? I'd like to avoid littering my
threaded code with huge numbers of unnecessary locks...

Thanks,
Paul.
-- 
This signature intentionally left blank




More information about the Python-list mailing list