3 ms·
> If the counter is atomic if I know you came to the same conclusion in another comments, but here's a look at it using the `dis` module: a += 1 turns i
by dkersten 5y ago
> If the counter is atomic
if
I know you came to the same conclusion in another comments, but here's a look at it using the `dis` module:
a += 1
turns into
LOAD_FAST 1 (loads b)
LOAD_CONST 1 (loads the constant 1)
INPLACE_ADD (perform the addition)
STORE_FAST 1 (store back into b)
So if the interpreter switches threads between LOAD_CONST and STORE_FAST (so either before or after the INPLACE_ADD), you could clobber the value another thread wrote to `b`.
From your other comment:
> so even though an increment on a loaded int is atomic, loading it and storing it aren't
Its always the loads and stores that are the problem.
But that's the problem with relying on the GIL: it has lock in the name, but it does not protect you, unless you understand the internals and know what you're doing. It protects the interpreter. This isn't much different from programming in other languages without a GIL: if you understand the internals what you're doing you may or may not need locks, because you will know what is and isn't atomic (and even when things are atomic, its still difficult to write thread-safe code! lock-free algorithms are much harder than using mutexes).
Thread safe code requires thinking hard about your code, the GIL does not protect you from that.
- dkersten 5y agoToo late to edit correction: between LOAD_FAST (not LOAD_CONST) and STORE_FAST