StackPractices
intermediate By Mathias Paulenko

Parallelize CPU and I/O Work with ThreadPoolExecutor

Use Python's ThreadPoolExecutor for parallel I/O operations, thread-safe result collection, Future callbacks, error handling, and mixing threads with asyncio for blocking work.

Overview

ThreadPoolExecutor from concurrent.futures runs callables across a fixed pool of worker threads — you submit work, get back Future objects, and collect results as they land. Threads share memory, so they’re cheap to start, but the GIL means they only truly run in parallel while waiting on I/O: HTTP calls, file reads, database queries. For that profile — dozens of network-bound tasks — a thread pool typically cuts wall time from seconds-per-request to the latency of the slowest one. Below: submit vs map, callbacks, per-future error handling, thread-local sessions, and bridging blocking code into asyncio.

When to Use This

  • Fanning out I/O-bound calls — HTTP requests, file downloads, database queries — where most of the time is spent waiting
  • Calling blocking libraries (requests, psycopg2, boto3) that have no async equivalent, especially from inside async code via run_in_executor
  • Running independent functions in parallel without rewriting them for async/await
  • Background jobs that can finish while the main thread keeps working

When NOT to Use This

  • CPU-bound work (number crunching, image processing) — threads serialize on the GIL; use ProcessPoolExecutor or free-threaded Python instead
  • Work that’s already async-native — asyncio.gather with aiohttp beats threads for thousands of concurrent connections
  • Tasks sharing mutable state without synchronization — you’ll trade speed for debugging race conditions

Prerequisites

  • Python 3.10+

Solution

1. Basic ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
import time

def fetch_url(url: str) -> dict:
    response = requests.get(url, timeout=10)
    return {'url': url, 'status': response.status_code, 'size': len(response.content)}

urls = [
    'https://api.example.com/users',
    'https://api.example.com/orders',
    'https://api.example.com/products',
    'https://api.example.com/inventory',
]

# Using context manager — pool is automatically shut down
start = time.time()
with ThreadPoolExecutor(max_workers=4) as executor:
    futures = {executor.submit(fetch_url, url): url for url in urls}

    for future in as_completed(futures):
        url = futures[future]
        try:
            result = future.result()
            print(f"{url}: {result['status']} ({result['size']} bytes)")
        except Exception as e:
            print(f"{url} failed: {e}")

print(f"Total time: {time.time() - start:.2f}s")

2. Using executor.map (Ordered Results)

from concurrent.futures import ThreadPoolExecutor

def process_item(item: int) -> int:
    import time
    time.sleep(0.5)
    return item * 2

items = list(range(10))

with ThreadPoolExecutor(max_workers=5) as executor:
    # map returns results in the SAME ORDER as input — unlike as_completed
    results = list(executor.map(process_item, items))

print(results)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

3. Future Callbacks

from concurrent.futures import ThreadPoolExecutor
import threading

def long_task(task_id: int) -> str:
    import time
    time.sleep(1)
    return f"Result of task {task_id}"

def on_complete(future):
    try:
        result = future.result()
        print(f"[Thread {threading.current_thread().name}] Callback: {result}")
    except Exception as e:
        print(f"Callback error: {e}")

with ThreadPoolExecutor(max_workers=3) as executor:
    futures = []
    for i in range(5):
        future = executor.submit(long_task, i)
        future.add_done_callback(on_complete)
        futures.append(future)

    # Wait for all to complete
    for future in futures:
        future.result()

4. Error Handling

from concurrent.futures import ThreadPoolExecutor, as_completed

def risky_task(task_id: int) -> str:
    if task_id == 2:
        raise ValueError(f"Task {task_id} intentionally failed")
    import time
    time.sleep(0.1)
    return f"Task {task_id} succeeded"

with ThreadPoolExecutor(max_workers=5) as executor:
    futures = {executor.submit(risky_task, i): i for i in range(5)}

    for future in as_completed(futures):
        task_id = futures[future]
        try:
            result = future.result(timeout=5)
            print(f"Success: {result}")
        except ValueError as e:
            print(f"Task {task_id} ValueError: {e}")
        except TimeoutError:
            print(f"Task {task_id} timed out")
        except Exception as e:
            print(f"Task {task_id} unexpected error: {type(e).__name__}: {e}")

5. Thread-Safe Result Collection

from concurrent.futures import ThreadPoolExecutor
from threading import Lock
import requests

class ThreadSafeResults:
    def __init__(self):
        self._results = []
        self._lock = Lock()
        self._errors = []

    def add_result(self, result):
        with self._lock:
            self._results.append(result)

    def add_error(self, error):
        with self._lock:
            self._errors.append(error)

    @property
    def results(self):
        with self._lock:
            return list(self._results)

    @property
    def errors(self):
        with self._lock:
            return list(self._errors)

def fetch_and_store(url: str, storage: ThreadSafeResults):
    try:
        response = requests.get(url, timeout=10)
        storage.add_result({'url': url, 'status': response.status_code})
    except Exception as e:
        storage.add_error({'url': url, 'error': str(e)})

storage = ThreadSafeResults()
urls = [f'https://api.example.com/data/{i}' for i in range(50)]

with ThreadPoolExecutor(max_workers=10) as executor:
    executor.map(lambda url: fetch_and_store(url, storage), urls)

print(f"Successes: {len(storage.results)}")
print(f"Failures: {len(storage.errors)}")

6. Mixing Threads with asyncio

import asyncio
from concurrent.futures import ThreadPoolExecutor
import requests

def blocking_fetch(url: str) -> dict:
    """Synchronous function that blocks — runs in a thread."""
    response = requests.get(url, timeout=10)
    return response.json()

async def fetch_all(urls: list) -> list:
    loop = asyncio.get_event_loop()

    # Run blocking function in thread pool — doesn't block the event loop
    with ThreadPoolExecutor(max_workers=10) as executor:
        tasks = [
            loop.run_in_executor(executor, blocking_fetch, url)
            for url in urls
        ]
        return await asyncio.gather(*tasks, return_exceptions=True)

# Or use asyncio.to_thread (Python 3.9+) for simpler cases
async def fetch_one(url: str) -> dict:
    return await asyncio.to_thread(blocking_fetch, url)

urls = [f'https://api.example.com/data/{i}' for i in range(20)]
results = asyncio.run(fetch_all(urls))

7. Chunked Processing

from concurrent.futures import ThreadPoolExecutor, as_completed
import requests

def process_chunk(chunk: list) -> list:
    """Process a chunk of URLs sequentially within one thread."""
    results = []
    for url in chunk:
        try:
            response = requests.get(url, timeout=10)
            results.append({'url': url, 'status': response.status_code})
        except Exception as e:
            results.append({'url': url, 'error': str(e)})
    return results

def process_in_chunks(urls: list, num_workers: int = 5) -> list:
    # Split URLs into chunks — one per worker
    chunk_size = (len(urls) + num_workers - 1) // num_workers
    chunks = [urls[i:i + chunk_size] for i in range(0, len(urls), chunk_size)]

    all_results = []
    with ThreadPoolExecutor(max_workers=num_workers) as executor:
        futures = {executor.submit(process_chunk, chunk): chunk for chunk in chunks}

        for future in as_completed(futures):
            all_results.extend(future.result())

    return all_results

urls = [f'https://api.example.com/data/{i}' for i in range(100)]
results = process_in_chunks(urls, num_workers=10)

8. ProcessPoolExecutor for CPU-Bound Work

from concurrent.futures import ProcessPoolExecutor
import math

def is_prime(n: int) -> bool:
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

def count_primes(start: int, end: int) -> int:
    return sum(1 for n in range(start, end) if is_prime(n))

# Use ProcessPoolExecutor for CPU-bound work — bypasses the GIL
ranges = [(0, 100000), (100000, 200000), (200000, 300000), (300000, 400000)]

with ProcessPoolExecutor(max_workers=4) as executor:
    futures = [executor.submit(count_primes, start, end) for start, end in ranges]
    total = sum(f.result() for f in futures)

print(f"Total primes: {total}")

How It Works

flowchart diagram: submit/map calls

submit() drops a callable on an internal queue and hands you a Future immediately. Idle worker threads pull tasks off that queue, so the pool keeps max_workers threads busy without paying the ~8MB stack cost of a thread per task. A Future is just a handle for a result that doesn’t exist yet — future.result() blocks until it does, and re-raises whatever the callable threw, which is why every result() call needs a try. map is the same machinery with a different return: an iterator that yields results in input order, blocking on each. The GIL is what makes all of this I/O-only — threads take turns running Python bytecode, but a thread holding the GIL drops it the moment it enters a blocking call, so network-bound tasks genuinely overlap. CPU-bound tasks never let go, which is why ProcessPoolExecutor (one GIL per process) is the escape hatch for computation.

Variants

Reusable Executor

from concurrent.futures import ThreadPoolExecutor

class WorkerPool:
    """Long-lived thread pool for repeated use."""
    def __init__(self, max_workers: int = 10):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)

    def submit(self, fn, *args, **kwargs):
        return self.executor.submit(fn, *args, **kwargs)

    def map(self, fn, *iterables):
        return self.executor.map(fn, *iterables)

    def shutdown(self):
        self.executor.shutdown(wait=True)

# Usage — keep the pool alive across multiple batches
pool = WorkerPool(max_workers=10)
results1 = list(pool.map(fetch_url, urls_batch1))
results2 = list(pool.map(fetch_url, urls_batch2))
pool.shutdown()

Thread-Local Storage

from concurrent.futures import ThreadPoolExecutor
import threading

thread_local = threading.local()

def init_session():
    if not hasattr(thread_local, 'session'):
        import requests
        thread_local.session = requests.Session()
    return thread_local.session

def fetch_with_reused_session(url: str) -> dict:
    session = init_session()  # Each thread gets its own session
    response = session.get(url, timeout=10)
    return {'url': url, 'status': response.status_code}

# Each thread reuses its own Session — connection pooling per thread
with ThreadPoolExecutor(max_workers=5) as executor:
    results = list(executor.map(fetch_with_reused_session, urls))

Best Practices

  • A runnable version of these patterns is in the companion repository.

  • For the async-native alternative, see Asyncio Semaphore Rate Limiting and the Complete Guide to Python Asyncio.

  • Use threads for I/O, processes for CPU: Threads are fine for HTTP requests and file I/O (GIL is released). For CPU-bound work, use ProcessPoolExecutor to bypass the GIL.

  • Size max_workers to the workload: For I/O-bound work, 5-20 workers is typical — each one mostly waits. More than ~50 rarely helps; the kernel spends its time context-switching.

  • Always use the context manager: with ThreadPoolExecutor() as executor shuts the pool down even when a result() call raises. A leaked executor keeps its threads alive and can hang the process on exit.

  • Use as_completed for progress: it yields futures as they finish, so you can stream results or update a progress bar. Use map when order matters.

  • Handle exceptions per-future: future.result() re-raises the original exception. Catch it per-future so one bad task doesn’t kill the batch.

  • Use thread-local for per-thread resources: database connections and HTTP sessions shouldn’t cross threads — threading.local() gives each worker its own.

Common Mistakes

  • Using threads for CPU-bound work: The GIL prevents true parallelism for computation. Use ProcessPoolExecutor instead.
  • Not handling exceptions: A future that raises stores the traceback and waits — nothing surfaces until result() gets called. Futures nobody checks are silent failures, so iterate them all or inspect future.exception().
  • Sharing mutable state without locks: Workers run in the same memory space, so two of them can interleave a read-modify-write and corrupt each other’s work. Guard shared state with threading.Lock, or better, return results through futures so nothing is shared at all.
  • Creating too many threads: Each thread consumes ~8MB of stack space. 1000 threads = 8GB of stack. Use a bounded pool.
  • Not shutting down the executor: Skip the context manager and executor.shutdown() becomes your job — forget it and the pool’s threads outlive main(), so the process never exits cleanly.

Further Reading

Frequently Asked Questions

When should I use ThreadPoolExecutor vs asyncio?

Threads when you're stuck with blocking libraries (requests, psycopg2, boto3) — wrapping them is cheaper than rewriting. Asyncio when you control the I/O layer (aiohttp, asyncpg) and need thousands of concurrent connections, since coroutines cost far less than threads.

How many workers should I use?

For I/O-bound work, somewhere in the 5-20 band covers most cases — each worker spends nearly all its time blocked on the network anyway. Don't guess: bump max_workers and watch wall time until it stops improving. For CPU-bound work the number is irrelevant because the GIL serializes everything; that's ProcessPoolExecutor territory.

Does Python 3.13 free-threading change the calculus?

Partially. With the free-threaded build (PYTHON_GIL=0), threads can run Python code in parallel, so CPU-bound threads start making sense — but library support is still catching up. On standard builds, the threads-for-I/O rule stands.

What happens to an exception raised inside a worker thread?

The traceback gets packed into the Future object — the crash doesn't propagate to the thread that submitted the work. Nothing is raised until future.result() runs, which means a batch can quietly drop half its tasks if you only look at successes. Walk every future's result() in a try, or audit future.exception().

Can two threads corrupt a shared list or dict?

Appends and single-item writes happen to be atomic in CPython, but compound operations (x += 1, read-modify-write) can interleave. Guard shared state with threading.Lock or collect through futures instead of shared structures.

Can I cancel a submitted future?

future.cancel() works only while the task is still queued — once a worker picks it up, cancellation returns False and the task runs to completion. Python deliberately has no API to kill a running thread; you'd corrupt whatever it was holding. Check future.cancelled() to see whether the cancel landed.