Standard Library
Threads and Processes
ThreadPoolExecutor runs square across two worker threads sharing the same interpreter (and the GIL); ProcessPoolExecutor runs pow across two child processes with isolated memory. Each pool.map returns an iterator over results in input order, and the surrounding with block joins the workers when the body exits. (This fragment runs in standard Python only — the Python By Example runner does not provide native threads or child processes.)
Standard Python
with ThreadPoolExecutor(max_workers=2) as pool:
print(list(pool.map(square, [1, 2, 3])))
with ProcessPoolExecutor(max_workers=2) as pool:
print(list(pool.map(pow, [4, 5], [2, 2])))A thread pool runs ordinary callables while sharing memory with the current process. map() returns results in input order.
Source
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def square(number):
return number * number
with ThreadPoolExecutor(max_workers=2) as pool:
print(list(pool.map(square, [1, 2, 3])))Output
[1, 4, 9]A process pool uses separate Python processes. That boundary is heavier, but it can run CPU-bound work outside the current interpreter.
Source
print(ProcessPoolExecutor.__name__)Output
ProcessPoolExecutorNotes
- Threads share memory, so mutable shared state needs care.
- Processes avoid shared interpreter state but require values to cross a process boundary.
- Prefer
asynciofor coroutine-based I/O and executors for ordinary blocking callables. - The displayed executor names are standard Python concepts; the site avoids actually creating host threads or processes in the live runner.
See also
- next depth: Async Await
- related: Subprocesses
- related: Networking
Run the complete example
Expected output
[1, 4, 9]
ProcessPoolExecutor
Execution time appears here after you run the example.