Full answer
python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def io_task(i):
time.sleep(0.1)
return i
def cpu_task(n):
return sum(i * i for i in range(n))
if __name__ == "__main__":
t0 = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as ex:
print(list(ex.map(io_task, range(5))))
print("threads overlap waits:", time.perf_counter() - t0 < 0.3)
with ProcessPoolExecutor(max_workers=2) as ex:
print(list(ex.map(cpu_task, [10**5, 10**5])))Output:
text
[0, 1, 2, 3, 4]
threads overlap waits: True
[333328333350000, 333328333350000]Five 0.1-second sleeps finish in about 0.1 seconds with five threads, because sleeping releases the GIL. The process pool computes two CPU-bound sums in separate processes, which can use two cores; arguments and results are pickled between processes, so they must be picklable and preferably small. The if __name__ == '__main__' guard is required for process pools on platforms that start workers by importing the main module. Process start-up costs time, so it pays off only for substantial work.
python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def io_task(i):
time.sleep(0.1)
return i
def cpu_task(n):
return sum(i * i for i in range(n))
if __name__ == "__main__":
t0 = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as ex:
print(list(ex.map(io_task, range(5))))
print("threads overlap waits:", time.perf_counter() - t0 < 0.3)
with ProcessPoolExecutor(max_workers=2) as ex:
print(list(ex.map(cpu_task, [10**5, 10**5])))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Threads and asyncio for I/O-bound work
- Processes for CPU-bound work
- concurrent.futures unifies pools
- Process arguments must be picklable
- Guard process code with __main__
Common mistakes
- Using threads for CPU-bound loops
- Sending large objects to process pools
Follow-ups
- What changes with the free-threaded build?
- How would you share data between processes?
Tips
- Classify the work first