Python · Exercise 6 of 6 Previous
Advanced
Process a batch with a queue and workers
square(n) returns n * n after a short wait. Write async def process_all(items, workers) that puts all items in an asyncio.Queue, starts workers worker tasks that take items from the queue and call square, waits until every item is handled (queue.join()), stops the workers, and returns the squares sorted from smallest to largest.
Use task_done() after each item. The program should print [1, 4, 9].
What Check tests
process_all([3, 1, 2], 2)returns the sorted squares- Two workers handle six items two at a time
- One worker handles items one at a time
- An empty batch returns an empty list and does not hang
- The solution uses asyncio.Queue
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.