Synchronization Primitives

Preview — 3 of 10 questions

What is the output of the following code?

javascript
import asyncio

running = 0
max_running = 0

async def worker(sem):
    global running, max_running
    async with sem:
        running += 1
        max_running = max(max_running, running)
        await asyncio.sleep(0.05)
        running -= 1

async def main():
    sem = asyncio.Semaphore(2)
    await asyncio.gather(*(worker(sem) for _ in range(5)))
    print(max_running)

asyncio.run(main())
A1
B5
C2
DTypeError: Semaphore() takes no arguments

What is the output of the following code?

javascript
import asyncio

async def waiter(event, results):
    await event.wait()
    results.append("waiter proceeded")

async def setter(event, results):
    results.append("before set")
    event.set()

async def main():
    event = asyncio.Event()
    results = []
    await asyncio.gather(waiter(event, results), setter(event, results))
    print(results)

asyncio.run(main())
A['before set', 'waiter proceeded']
BBoth coroutines hang forever, since the event is never set before waiter checks it.
C['waiter proceeded', 'before set']
DTypeError: Event() takes no arguments

What is the output of the following code?

javascript
import asyncio

async def slow():
    await asyncio.sleep(0.1)
    return "slow"

async def fast():
    await asyncio.sleep(0.01)
    return "fast"

async def main():
    results = []
    for coro in asyncio.as_completed([slow(), fast()]):
        result = await coro
        results.append(result)
    print(results)

asyncio.run(main())
ATypeError: as_completed() takes no arguments
BAlways matches input order, just like gather().
C['slow', 'fast']
D['fast', 'slow']

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.