Thread-safe way to add a key to a dict only if it isn't already there?

Marko Rauhamaa marko at pacujo.net
Sun Jul 8 03:52:15 EDT 2018


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
>>> parallel:
>>>
>>>     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.

   <URL: https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.htm
   l#jls-17.4.5>

And we know that Python has been implemented using Java...


Marko


More information about the Python-list mailing list