[Python-Dev] PyFAQ: thread-safe interpreter operations

"Martin v. Löwis" martin at v.loewis.de
Tue Nov 21 23:24:21 CET 2006


Armin Rigo schrieb:
> Or, more interestingly, the same is true for constructs like 'd[x]+=1':
> they are a sequence of three bytecodes that may overlap other threads
> (read d[x], add 1, store the result back in d[x]) so it's not a
> thread-safe way to increment a counter.
> 
> (More generally it's very easy to forget that expr1[expr2] += expr3
> really means
> 
>     x = expr1;  y = expr2;  x[y] = x[y] + expr3
> 
> using a '+' that is special only in that it invokes the __iadd__ instead
> of the __add__ method, if there is one.)

OTOH, using += is "thread-safe" if the object is mutable (e.g. a list),
and all modifications use +=. In that case, __iadd__ will be invoked,
which may (for lists) or may not (for other types) be thread-safe.
Since the same object gets assigned to the original slot in all
threads, execution order does not really matter.

I personally consider it "good style" to rely on implementation details
of CPython; if you do, you have to know precisely what these details
are, and document why you think a specific fragment of code is correct.

Regards,
Martin


More information about the Python-Dev mailing list