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

Chris Angelico rosuav at gmail.com
Sun Jul 8 00:03:38 EDT 2018


On Sun, Jul 8, 2018 at 1:58 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 08 Jul 2018 12:23:41 +1000, Chris Angelico wrote:
>
>>> Some people, when confronted with a problem, say, "I know, I'll use
>>> threads". Nothhtwo probw ey ave lems.
>>
>> Right. Now they have to deal with interleaving, but that's all. And
>> honestly, MOST CODE wouldn't notice interleaving; it's only when you
>> change (either by rebinding or by mutating) something that can be seen
>> by multiple threads. Which basically means "mutable globals are a risk,
>> pretty much everything else is safe".
>
> Its not just globals though. Any mutable object shared between two
> threads is potentially a risk. Globals are just the most obvious example.
>

Right; by "basically" I mean "yes there are others but this is what
matters". The technically-accurate part is in the previous sentence:
"can be seen by multiple threads".

ChrisA


More information about the Python-list mailing list