3 ms·
In the Python VM there is no atomic increment bytecode. So `counter += 1` should be exactly same as `counter = counter + 1`. Here is an example what thread sa
by miohtama 5y ago
In the Python VM there is no atomic increment bytecode. So `counter += 1` should be exactly same as `counter = counter + 1`.
Here is an example what thread safe increment looks like in Python:
https://julien.danjou.info/atomic-lock-free-counters-in-python/ https://julien.danjou.info/atomic-lock-free-counters-in-pyth...
You need to lock it explicitly.
Note that `INC` instructor for x86 architecture needs explicit hints/locks as well, so this should suprise anyone:
https://stackoverflow.com/q/10109679 https://stackoverflow.com/q/10109679
- jasonhansel 5y agoIn general, "+=" probably needs to be non-atomic to support "__add__" overloading; Python wouldn't be able to call arbitrary "__add__" methods in a way that could guarantee atomicity.
- nneonneo 5y agoA bit more detail: there is an atomic addition bytecode, called INPLACE_ADD, which is why something like “a_list += [1]” is actually atomic. The problem is that integers are immutable, so “counter += 1” involves a (non-atomic) load and store of counter, and that’s where the race is. Hypothetically, if Python had a built-in mutable integer type, the increment could be made atomic.