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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 7 22:12:47 EDT 2018


On Sun, 08 Jul 2018 11:15:17 +1000, Chris Angelico wrote:

[...]
> Python threads don't switch only between lines of code, 

As I understand it, there could be a switch between any two byte codes, 
or maybe only between certain bytes codes. But certain more fine grained 
than just between lines of code.


> so the actual
> interaction is a bit more complicated than you say. In CPython, the
> increment operation is:
> 
>   3           0 LOAD_GLOBAL              0 (i)
>               2 LOAD_CONST               1 (1)
>               4 INPLACE_ADD
>               6 STORE_GLOBAL             0 (i)
> 
> A context switch could happen between any pair of statements.

If you actually mean *statements* as opposed to byte codes, then the only 
place there could be a switch would be either before the LOAD_GLOBAL or 
after the STORE_GLOBAL (given that i is a built-in int and cannot have a 
custom __iadd__ method).

Is that what you mean?


> In this
> particular example, the end result doesn't change - coherent results are
> 2 and 3, nothing else - but in other situations, there may be times when
> the separate steps might be significant.

Fortunately I wasn't talking about other code snippets, only the one 
shown :-)


> For instance, if you replace "i
> += 1" with "i += i", to double the value, you'll get this:
> 
>   3           0 LOAD_GLOBAL              0 (i)
>               2 LOAD_GLOBAL              0 (i)
>               4 INPLACE_ADD
>               6 STORE_GLOBAL             0 (i)
> 
> and that could potentially have both of them load the initial value,
> then one of them runs to completion, and then the other loads the result
> - so it'll add 1 and 2 and have a result of 3, rather than 2 or 4.

Some people, when confronted with a problem, say, "I know, I'll use 
threads". Nothhtwo probw ey ave lems.



> But you're absolutely right that there are only a small handful of
> plausible results, even with threading involved.

Indeed. Even though threading is non-deterministic, it isn't *entirely* 
unconstrained.



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list