All quizzesHard
Synchronization Primitives — Series 3
Preview — 3 of 10 questions
What is the output of the following code?
javascript
import asyncio
async def worker():
try:
await asyncio.sleep(1)
except asyncio.CancelledError as e:
print("cancelled with args:", e.args)
raise
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.01)
task.cancel("shutting down")
try:
await task
except asyncio.CancelledError:
print("main sees cancellation")
asyncio.run(main())Acancelled with args: ('shutting down',), main sees cancellation
Bcancelled with args: (), main sees cancellation
Cmain sees cancellation, cancelled with args: ('shutting down',)
DTypeError: cancel() takes 1 positional argument but 2 were given
What is the output of the following code?
javascript
import asyncio
results = []
async def runner(barrier, n):
results.append(f"{n} waiting")
await barrier.wait()
results.append(f"{n} passed")
async def main():
barrier = asyncio.Barrier(3)
await asyncio.gather(runner(barrier, 1), runner(barrier, 2), runner(barrier, 3))
waiting_count = sum(1 for r in results if "waiting" in r)
passed_count = sum(1 for r in results if "passed" in r)
first_passed_index = next(i for i, r in enumerate(results) if "passed" in r)
print(waiting_count, passed_count)
print(all("waiting" in results[i] for i in range(first_passed_index)))
asyncio.run(main())ATimeoutError — a barrier requires an explicit release call
B3 3, True
C3 3, False
D1 1, True
What is the output of the following code?
javascript
import asyncio
async def main():
loop = asyncio.get_running_loop()
deadline = loop.time() + 0.05
try:
async with asyncio.timeout_at(deadline):
await asyncio.sleep(1)
except TimeoutError:
print("TimeoutError")
asyncio.run(main())ATypeError: timeout_at() takes a relative delay, not an absolute time
BTimeoutError after roughly a full second
CTimeoutError
DNothing prints; the sleep(1) completes normally
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.