Races and locks

A race condition is a bug where the result depends on the order tasks run in. The classic one: two tasks each read a shared counter, both add one, and both write it back. One update is lost.

With asyncio, tasks only switch at an await. So count += 1 on its own is safe. But "read, await something, then write" is not: another task can run in the gap and its write gets overwritten.

The fix is a lock. async with lock: lets one task at a time into the block, so the read and the write happen together. Threads have the same problem, and worse, since they can switch between almost any two bytecodes; there you use threading.Lock.

Interviewers love this question. Say what the shared state is, where the gap is, and how the lock closes it. Better still, avoid shared state: have each task return its result and combine them at the end.

Run it. The unsafe counter loses updates. Then move the await in unsafe_add to after the write and see it come out right.