[Python-Dev] PyFAQ: thread-safe interpreter operations
arigo at tunes.org
Tue Nov 21 22:56:20 CET 2006
On Tue, Nov 21, 2006 at 09:24:07PM +0100, "Martin v. L?wis" wrote:
> As for the original questions: "x+=1" is two "atomic"
> operations, not one. Or, more precisely, it's 4 opcodes,
> not 2.
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
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.)
More information about the Python-Dev