atomic operations in presence of multithreading

Glenn Kasten gkasten9 at
Tue Jul 27 20:01:58 CEST 2004

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?
For example, initially:
   dictionary = {}
   dictionary[key] = old_value
Then thread 1 does:
   v = dictionary[key]
And thread 2 does:
   dictionary[key] = new_value2
And thread 3 does:
   dictionary[key] = new_value3
What I want to make sure of is that 
thread 1 will read either the old_value
for key, or new_value2, or new_value3,
but not an intermediate value.
Which value in particular does not matter to me, as that
obviously depends on timing. I just want to make sure
that the dictionary internal data structures can't
become corrupted by multiple writers / readers.
Note: I realize that in this particular case
I can use locks to guarantee safety, but I am
wondering whether the basic language operations
such as dictionary reads and updates are guaranteed
to be atomic.
A related, more general question, is which
Python operations are atomic, and which are not.
I was unable to find this in the language reference,
but please direct me to the correct location
if I missed it.

More information about the Python-list mailing list