Editor

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 lesson

Build 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}".

    # Build the TaskQueue class
    # Create queue, add tasks, run, print results

    More Concurrency exercises

    All Python exercises · 50 practice problems · Advanced Python quiz