
The Leaky Fuel Tank
Fifty keepers each pour 1 unit of fuel into the guild tank. The tank should read 50. It reads 1. Fuel is vanishing!
What went wrong: a race condition
Each deposit does read, then wait, then write:
- Keeper A reads
fuel = 0, then awaits (a slow write). - While A waits, keeper B also reads
fuel = 0. - A writes
0 + 1. B writes0 + 1. One deposit is lost.
This happens whenever tasks share data and the program can switch tasks
between the read and the write. With asyncio that's any await. With
threads it can happen anywhere.
The fix: a lock
An asyncio.Lock lets only one task at a time into a critical
section:
async with lock:
... # only one task at a time in here
Other tasks wait at the door until the lock is released. (Threads use
threading.Lock, which works the same way.)
Assignment
The code even creates a lock, but deposit never uses it. Fix deposit
so the whole read–wait–write runs inside async with lock:. Keep the
await asyncio.sleep(0), because it stands in for a real slow write.
The code even creates a lock, but deposit never uses it. Fix deposit
so the whole read–wait–write runs inside async with lock:. Keep the
await asyncio.sleep(0), because it stands in for a real slow write.
Press Run to try your code, then Check to test it.