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
- Threads and the GIL
- ThreadPoolExecutor
- multiprocessing Basics
- Sharing Data Safely