Build a Task Queue
Advanced · Write the code · from Python Threading vs Multiprocessing vs asyncio: When to Use What
From the lesson: Python Threading vs Multiprocessing vs asyncio: When to Use What
Most programs you've written so far do one thing at a time. But real applications need to handle multiple tasks: downloading files while updating a progress bar, serving web requests from many users, or crunching numbers across all CPU cores.
Read the lessonBuild a TaskQueue class that simulates a concurrent task processor:
1. __init__ creates an empty list self.tasks and an empty list self.results
2. add_task(name, func, arg) appends a tuple (name, func, arg) to tasks
3. run_all() processes each task by calling func(arg), storing (name, result) in results
4. get_results() returns the results list
Create a queue, add three tasks:
("square", lambda x: x**2, 5)("double", lambda x: x*2, 7)("negate", lambda x: -x, 3)Run all tasks and print each result as "{name}: {result}".
More Concurrency exercises
- Concurrency Decision MakerAdvanced
- Build a Thread-Safe CounterAdvanced
- Predict the Output: asyncio.gatherAdvanced
- Fix the Bug: Missing LockAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz