Threading and Multiprocessing with Concurrent Futures
Implement concurrent I/O with ThreadPoolExecutor and parallel multi-core computations with ProcessPoolExecutor using Python's concurrent.futures module.
When you need to execute multiple tasks at once in Python, you have two primary execution models:
- Threads: Multiple workers sitting in the same office sharing the exact same memory space. Fast to create and lightweight, but subject to the CPython GIL.
- Processes: Multiple independent workers in separate buildings with their own private memory and Python interpreters. Heavier on RAM, but capable of true multi-core parallel computation.
Historically, Python developers wrestled with manual thread creation and lock management. Today, Python provides the high-level concurrent.futures module, giving you a clean, unified pool abstraction for both threads and processes!
1. ThreadPoolExecutor: Concurrent I/O Tasks
Suppose you need to download data from 5 different web services. If each request takes 0.5 seconds, running them sequentially one after another takes $5 \times 0.5 = 2.5$ seconds.
With ThreadPoolExecutor, all 5 requests fire concurrently, finishing in just 0.5 seconds total:
import time
from concurrent.futures import ThreadPoolExecutor
def fetch_data(service_id):
print(f"[{service_id}] Request sent...")
time.sleep(0.5) # Simulates waiting for network I/O
print(f"[{service_id}] Response received!")
return f"Service {service_id}: Status 200 OK"
services = ["Auth", "Billing", "Analytics", "Inventory", "Notifications"]
start_time = time.perf_counter()
# Launch a pool of 5 worker threads
with ThreadPoolExecutor(max_workers=5) as executor:
# executor.map applies fetch_data to all items concurrently!
results = list(executor.map(fetch_data, services))
elapsed = time.perf_counter() - start_time
print(f"\nAll 5 requests finished in {elapsed:.2f} seconds!")
print("Collected results:", results)
Output:
[Auth] Request sent...
[Billing] Request sent...
[Analytics] Request sent...
[Inventory] Request sent...
[Notifications] Request sent...
[Auth] Response received!
[Billing] Response received!
[Analytics] Response received!
[Inventory] Response received!
[Notifications] Response received!
All 5 requests finished in 0.52 seconds!
2. ProcessPoolExecutor: Parallel CPU-Bound Crunching
For CPU-intensive calculations (like calculating prime numbers, encrypting files, or rendering graphics), threads cannot bypass the GIL.
Use ProcessPoolExecutor to distribute work across all physical CPU cores:
import os
import time
from concurrent.futures import ProcessPoolExecutor
def heavy_computation(number):
"""Simulates a heavy CPU mathematical workload."""
total = sum(i * i for i in range(number))
return f"Core {os.getpid()} calculated sum for {number}"
def main():
workloads = [10_000_000, 10_000_000, 10_000_000, 10_000_000]
start = time.perf_counter()
# Spawns separate OS processes matching CPU hardware cores:
with ProcessPoolExecutor() as executor:
results = list(executor.map(heavy_computation, workloads))
duration = time.perf_counter() - start
print(f"Multi-core execution completed in {duration:.2f} seconds.")
for res in results:
print(" ", res)
# MANDATORY on Windows and macOS:
if __name__ == "__main__":
main()
[!CRITICAL] Always guard multiprocessing code with
if __name__ == "__main__":! On Windows and macOS, worker processes initialize by importing your script. Without this guard, each child process attempts to spawn its own child processes in an infinite fork bomb that crashes your computer!
3. map() vs submit(): Granular Task Management
concurrent.futures offers two ways to dispatch jobs:
1. executor.map(func, iterable)
- Simplest: works just like the built-in
map(). - Guarantees results return in the original input order.
2. executor.submit(func, *args)
- Returns a
Futureobject (a promise representing an eventual result). - Lets you check if tasks are running (
future.running()), done (future.done()), or retrieve results as they finish (as_completed):
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def task(name, delay):
time.sleep(delay)
return f"Task {name} completed in {delay}s"
with ThreadPoolExecutor(max_workers=3) as executor:
# Submit tasks with different durations
futures = [
executor.submit(task, "A", 0.3),
executor.submit(task, "B", 0.1),
executor.submit(task, "C", 0.2)
]
# Process results immediately as each one finishes (B, then C, then A!)
for future in as_completed(futures):
print(future.result())
Output:
Task B completed in 0.1s
Task C completed in 0.2s
Task A completed in 0.3s
4. Shared State and Race Conditions
When multiple threads read and write to the same variable simultaneously, a Race Condition can corrupt your data:
# Unsafe multi-threaded counter:
total = 0
def increment():
global total
for _ in range(100_000):
total += 1 # Race condition: two threads read total at the same time!
To ensure thread safety, protect shared variables using a Lock:
import threading
total = 0
lock = threading.Lock()
def safe_increment():
global total
for _ in range(100_000):
# Only one thread can enter this block at a time:
with lock:
total += 1
Summary & What’s Next
- Use
concurrent.futuresfor clean, pool-based concurrent workflows. ThreadPoolExecutorruns concurrent I/O operations (network, disk).ProcessPoolExecutorruns parallel CPU calculations across multiple physical cores.- Always use
if __name__ == "__main__":when working with multiprocessing. - Protect shared memory in multi-threaded programs using
threading.Lock.
Threads have overhead: every operating system thread consumes megabytes of memory. What if you need a web server that handles 50,000 requests simultaneously on a single thread? That brings us to asyncio.