Predict the output
A hundred tasks each 'increment' a counter. What's printed?
import asyncio
counter = 0
async def increment() -> None:
global counter
seen = counter
await asyncio.sleep(0)
counter = seen + 1
async def main() -> None:
async with asyncio.TaskGroup() as tg:
for _ in range(100):
tg.create_task(increment())
print(counter)
asyncio.run(main())Hint 1 of 1
What happens at the await?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1
Correct. Every task reads 0, yields at the await, then writes 0 + 1.
An await is a point where other tasks can run. All 100 tasks read 0 before any of them resumes and writes, so each writes 0 + 1 and the updates overwrite each other.
Why not the others?
- B
100. That needs each read and write to happen without a pause between them. - C A random number between 1 and 100. Scheduling here is deterministic: all reads run before any write.
- D
0. Every task writes 1.