0Pricing
Python Academy · Lesson

ThreadPoolExecutor

Run tasks concurrently.

Why a Thread Pool?

Creating and joining threads by hand is tedious. concurrent.futures.ThreadPoolExecutor manages a pool of worker threads for you and gives back results cleanly.

from concurrent.futures import ThreadPoolExecutor

def square(n):
    return n * n

with ThreadPoolExecutor() as ex:
    future = ex.submit(square, 5)
    print(future.result())

submit and Future

submit() schedules a call and immediately returns a Future. You call .result() on it to get the value, blocking until it is ready.

from concurrent.futures import ThreadPoolExecutor

def greet(name):
    return 'hi ' + name

with ThreadPoolExecutor(max_workers=2) as ex:
    f1 = ex.submit(greet, 'Ana')
    f2 = ex.submit(greet, 'Bob')
    print(f1.result())
    print(f2.result())

All lessons in this course

  1. Threads and the GIL
  2. ThreadPoolExecutor
  3. multiprocessing Basics
  4. Sharing Data Safely
← Back to Python Academy