Immutable object thread-safety
Alcari The Mad
AlcariTheMad at gmail.com
Mon Oct 27 02:53:50 CET 2008
Laszlo Nagy wrote:
>> Also, the other question is the operation st = 'ThreadBWasHere' is
> 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.
You are correct.
a,b = b,a
yields the bytecode:
1 0 LOAD_NAME 0 (b)
3 LOAD_NAME 1 (a)
7 STORE_NAME 1 (a)
10 STORE_NAME 0 (b)
Which is most definitely not 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. :-)
'a = b' requires two bytecodes:
1 0 LOAD_NAME 0 (b)
3 STORE_NAME 1 (a)
>> I mean, if Python does not guarantee if an immutable object
>> assignment is atomic, then how can we say that the object is thread-
> An assigment rebinds name to an object. It is assignment to a name.
> Assigning immutable and mutable objects to names are not specially
>> 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.
I would suggest reading up on using the 'with' statement and
More information about the Python-list