Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You possibly need to think a bit harder about exactly what it means to be thread safe. Consider if you wrote this code instead:</p> <pre><code>class SomeSharedData(object): def __init__(self): self.errors = 0 </code></pre> <p>This code is <strong>exactly</strong> as thread-safe as the code that you posted. Assigning a value to an attribute is thread safe in Python: the value is always assigned; it may or may not be overwritten by another value assigned from another thread, but you always get one value or the other, never a mix of the two. Likewise accessing the attribute gives you the current value.</p> <p>Where your code breaks is that as you said with either your original or the simplified version, a line such as:</p> <pre><code>shared.errors += 1 </code></pre> <p>is not thread safe, but that's the whole point of making you code safe, those are the things you need to watch out for, not the simple get/set.</p> <p>Answering the question in the comment:</p> <p>Simple assignment in Python is simply rebinding a name (not making a copy) and is guaranteed atomic; you get one value or the other. However assigning to an attribute (or subscripted variable) could be overridden as in your property above. In that case attribute assignment could potentially break. So the answer is that attribute assignment is usually safe but not if it has been over-ridden with a property or <strong>setattr</strong> or similar.</p> <p>Also, if the old value that is being replaced is a Python class with a destructor, or something that contains a Python class with a destructor then the destructor code could run in the middle of the assignment. Python will still ensure its own data structures don't get corrupted (so you should never get a segfault) but it won't do the same for your own. The obvious fix for this is never ever to define <strong>del</strong> on any of your classes.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload