Thread-safe way to add a key to a dict only if it isn't already there?
Chris Angelico <rosuav at gmail.com>:
> On Sun, Jul 8, 2018 at 11:04 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>>> The only thing Python should guarantee is that the data structures stay
>>> "coherent" under race conditions. In other words, there cannot be a
>>> segmentation fault. For example, if two threads executed this code in
>>> global i
>>> i = 1
>>> i += 1
>>> a legal end result could be that i contains the string "impossible".
>> That wouldn't be coherent. The only coherent results are that i could
>> equal either 2 or 3:
> Python threads don't switch only between lines of code, so the actual
> interaction is a bit more complicated than you say. [...]
> But you're absolutely right that there are only a small handful of
> plausible results, even with threading involved.
You are on the right track, Chris, but you are still deducing behavior
from a particular implementation. For example Java's definition is
approximately the one I give above:
Without correct synchronization, very strange, confusing and
counterintuitive behaviors are possible.
And we know that Python has been implemented using Java...