A non-atomic operation looks like one action but consists of multiple steps that can be interleaved with another concurrent operation. Incrementing an integer, for example, reads its value, adds one, and writes the result back. section 6.5.1 section 11.1
Non-atomic operations create different risks depending on the concurrency model:
- With multiple processes or threads, two workers can read the same value and overwrite each other’s updates, producing a race condition and corrupted data. section 6.5.1 section 11.1
- With asyncio, one thread executes one line at a time, so an ordinary non-atomic sequence completes without another coroutine observing its intermediate state. section 11.1
- Asyncio can still expose a race when an await splits the sequence, allowing another task to run between reading and writing shared state. section 11.1
A shared counter
Two processes incrementing a shared counter may both read zero, calculate one, and write one, leaving the final value at one instead of two. Repeating the test exposes the intermittent failure. In asyncio, inserting an await between the temporary increment and the final assignment creates the same lost-update pattern.
