Immutable object thread-safety

Laszlo Nagy gandalf at shopzeus.com
Sun Oct 26 18:18:46 EDT 2008


> Also, the other question is the operation st = 'ThreadBWasHere' is
> atomic? 
I think this is the same question. And I believe it is not atomic, 
because it is actually rebinding a name. Consider this:

a,b = b,a

This will rebind both a and b. In order to be correct, it MUST happen in 
two phases: first calculate the right side, then do the rebind to the 
names on the left side. The expression on the right side can be anything 
that executes for a long time, and can even rebind 'a' and 'b' several 
times, and will probably be paused by other threads etc. So the 
assignment above cannot be atomic.

I strongly feel that if such an assignment is not atomic for "a,b = b,a" 
then int wont be atomic for "a+=b" or eveb "a=b" or any other 
assignment. However, I can be completely wrong. :-)
> I mean, if Python does not guarantee if an immutable object
> assignment is atomic, then how can we say that the object is thread-
> safe? 
An assigment rebinds name to an object. It is assignment to a name. 
Assigning immutable and mutable objects to names are not specially 
distinguished.
> So, if it is an atomic operation, which operators are atomic,
> means only assignment'='? 
I don't think that '=' operator is atomic, see above.
> I am confused about which data structure to rely on thread-safety, or
> operator in Python?
>   
The immutable object itself will never change state, so it is thread 
safe. The problem is not with the object, but the dictionary which holds 
the name 'b' and 'a' and 'st' in your example. It is mutable, and so 
must be protected in a threaded application.

Best,

  Laszlo




More information about the Python-list mailing list