Are python objects thread-safe?
duncan.booth at invalid.invalid
Tue Dec 23 14:30:25 CET 2008
Aaron Brady <castironpi at gmail.com> wrote:
> Th.1 Th.2
> You are saying that if 'a=Z' interrupts 'a=Y' at the wrong time, the
> destructor for 'X' or 'Y' might not get called. Correct? In serial
> flow, the destructor for X is called, then Y.
No, the destructors will be called, but the destructors can do pretty much
anything they want so you can't say the assignment is atomic. This isn't
actually a threading issue: you don't need multiple threads to experience
werid issues here. If you do strange things in a destructor then you can
come up with confusing code even with a single thread.
>> Other nasty things can happen if you use dictionaries from multiple
>> threads. You cannot add or remove a dictionary key while iterating over
>> a dictionary. This isn't normally a big issue, but as soon as you try to
>> share the dictionary between threads you'll have to be careful never to
>> iterate through it.
> These aren't documented, IIRC. Did you just discover them by trial
> and error?
It is documented, but I can't remember where for Python 2.x. For Python 3,
PEP 3106 says: "As in Python 2.x, mutating a dict while iterating over it
using an iterator has an undefined effect and will in most cases raise a
RuntimeError exception. (This is similar to the guarantees made by the Java
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list