
Code
The Parcel Queue
An asyncio.Queue connects coroutines like a conveyor belt. Producers
put items on it and consumers take them off:
queue = asyncio.Queue(maxsize=2)
await queue.put("oil") # waits if the queue is full
item = await queue.get() # waits if the queue is empty
maxsize gives you backpressure. A fast producer has to wait for a
slow consumer instead of piling up a mountain of items in memory.
How does the consumer know when to stop? A common trick is a sentinel,
a special "no more items" value such as None:
while True:
item = await queue.get()
if item is None:
break
handle(item)
(For long-running workers there's also queue.task_done() and
await queue.join(), which waits until every item has been processed.)
In the starter, main() wraps the work in asyncio.timeout(2) as a
safety net. If you forget the sentinel, the courier would wait forever.
The timeout turns that freeze into a clear TimeoutError.
Assignment
producer(queue, parcels): put each parcel on the queue, then putNone.courier(queue, delivered): keep taking items off the queue. Stop when you getNone. For every other item, append"delivered <item>"to thedeliveredlist.
producer(queue, parcels): put each parcel on the queue, then putNone.courier(queue, delivered): keep taking items off the queue. Stop when you getNone. For every other item, append"delivered <item>"to thedeliveredlist.
main.py Python sleeping
Press Run to try your code, then Check to test it.