Standard Library
Threads and Processes
ThreadPoolExecutor runs square across worker threads that share this interpreter and its GIL; map() returns results in input order, and the with block joins the workers when the body exits. The in-browser sandbox cannot create native threads, so pressing Run here fails; this thread-pool output was produced under standard CPython at build time.
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]ProcessPoolExecutor is the heavier boundary: separate Python processes with isolated memory, for CPU-bound work that the GIL would otherwise serialise. The sandbox cannot spawn processes either, so this cell only inspects the class name rather than running a pool.
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 thread-pool output came from real worker threads under standard CPython at build time; the in-browser sandbox cannot create threads or processes, so live runs of this page fail there.
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.