Python concurrency is the practice of structuring a program so that multiple operations can make progress during overlapping periods of time. Concurrency is useful when an application needs to handle many independent operations without waiting for each one to finish before starting the next.
Python provides several concurrency models rather than one universal solution. Depending on the workload, you may use
threading,
multiprocessing,
concurrent.futures,
or
asyncio.
The correct choice depends mainly on whether the workload is I/O-bound, CPU-bound, or a mixture of both.
In normal CPython builds, the Global Interpreter Lock, or GIL, limits multiple threads from executing Python bytecode simultaneously. Threads can still be very effective for I/O-bound workloads, while process-based approaches can provide CPU parallelism. Modern CPython also has optional free-threaded builds and, in Python 3.14, an
InterpreterPoolExecutor
for isolated interpreter-based parallel execution. :contentReference[oaicite:0]{index=0}
What You Will Learn
- What concurrency means and how it differs from parallelism
- When to use threads and when to use processes
- How the GIL affects Python concurrency
- How to use ThreadPoolExecutor and ProcessPoolExecutor
- How Futures represent asynchronous results
- How multiprocessing works and why data must often be serialized
- How to protect shared state with locks and other synchronization tools
- How queues support producer-consumer architectures
- How asyncio differs from thread and process concurrency
- How to choose a practical concurrency strategy
Concurrency vs Parallelism
Concurrency and parallelism are related but different ideas. Concurrency means multiple tasks can make progress during overlapping periods. Parallelism means multiple pieces of work actually execute at the same time on different execution resources.
Concurrency
Task A: ====wait====work====wait====
Task B: ==work====wait====work====
Parallelism
CPU Core 1: Task A ========
CPU Core 2: Task B ========
An I/O-heavy program can benefit greatly from concurrency because one operation may be waiting while another progresses. CPU-heavy work may benefit more from actual parallel execution across CPU cores.
Common Python Concurrency Models
| Model | Best Fit | Shared Memory | Typical Trade-off |
|---|---|---|---|
| threading | I/O-bound work | Yes | Synchronization and GIL considerations |
| multiprocessing | CPU-bound work | No, by default | Higher process and data-transfer overhead |
| ThreadPoolExecutor | Many independent I/O tasks | Yes | Thread safety still matters |
| ProcessPoolExecutor | Many independent CPU tasks | No, by default | Arguments and results generally need serialization |
| asyncio | High-concurrency async I/O | Single event-loop thread by default | Blocking code must not stall the event loop |
Python Threads
The
threading
module allows multiple threads to execute within the same process. Threads share the process's memory, which makes communication convenient, but also means that shared mutable state must be handled carefully.
Threads are commonly used for workloads such as network requests, file operations, waiting for external services, and other tasks where the application spends a significant amount of time blocked on I/O. In standard CPython builds, the GIL limits simultaneous execution of Python bytecode across threads, so threads are generally not the first choice for CPU-bound pure-Python workloads. :contentReference[oaicite:1]{index=1}
import threading
import time
def download(name):
print(f"Starting {name}")
time.sleep(2)
print(f"Finished {name}")
thread1 = threading.Thread(
target=download,
args=("File A",)
)
thread2 = threading.Thread(
target=download,
args=("File B",)
)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("All downloads completed")
Both threads can spend their waiting time independently instead of forcing one operation to finish before the next starts.
Starting and Joining Threads
Calling
start()
schedules the thread to execute its target function. Calling
join()
makes the current thread wait for another thread to finish.
thread.start()
# Main program continues here
thread.join()
# Thread has completed here
Forgetting to join important worker threads can make application shutdown and result handling harder to reason about.
ThreadPoolExecutor
Creating threads manually is useful for learning and for simple cases, but production code often benefits from a thread pool. Python's
concurrent.futures
module provides the high-level
ThreadPoolExecutor
interface for running callables concurrently using a pool of worker threads. :contentReference[oaicite:2]{index=2}
from concurrent.futures import ThreadPoolExecutor
import time
def download(file_name):
print(f"Downloading {file_name}")
time.sleep(2)
return f"{file_name} completed"
files = [
"a.txt",
"b.txt",
"c.txt",
"d.txt"
]
with ThreadPoolExecutor(
max_workers=3
) as executor:
results = executor.map(
download,
files
)
for result in results:
print(result)
The executor manages worker threads so application code can focus on submitting work and consuming results rather than manually managing every thread.
What Is a Future?
A
Future
represents an operation whose result may become available later. When you submit a callable to an executor, the executor returns a Future that can be inspected or awaited synchronously using methods such as
result().
from concurrent.futures import ThreadPoolExecutor
def calculate(value):
return value * value
with ThreadPoolExecutor(
max_workers=2
) as executor:
future = executor.submit(
calculate,
10
)
result = future.result()
print(result)
A Future can also be checked for completion, cancellation, and exceptions. It is important not to confuse
concurrent.futures.Future
with
asyncio.Future;
they belong to different concurrency models. :contentReference[oaicite:3]{index=3}
Handling Future Exceptions
Exceptions raised inside executor workers become available when the Future's result is retrieved.
from concurrent.futures import ThreadPoolExecutor
def divide(a, b):
return a / b
with ThreadPoolExecutor(
max_workers=2
) as executor:
future = executor.submit(
divide,
10,
0
)
try:
print(future.result())
except ZeroDivisionError:
print("Cannot divide by zero")
as_completed()
Sometimes you want to process results as soon as individual tasks finish rather than waiting for results in submission order. The
as_completed()
helper provides that behavior.
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
import random
def work(item):
delay = random.uniform(1, 3)
time.sleep(delay)
return item
items = ["A", "B", "C", "D"]
with ThreadPoolExecutor(
max_workers=4
) as executor:
futures = [
executor.submit(work, item)
for item in items
]
for future in as_completed(futures):
print(
"Completed:",
future.result()
)
This is useful when early results can be consumed immediately instead of being held until slower tasks complete.
The Global Interpreter Lock
The GIL is one of the most important concepts in Python concurrency discussions. In standard CPython builds, a thread must hold the GIL to execute Python code, which prevents multiple threads from simultaneously executing ordinary Python bytecode in the same interpreter. :contentReference[oaicite:4]{index=4}
This does not mean threads are useless. The GIL does not eliminate concurrency, and blocking I/O operations can release the interpreter lock. Threading therefore remains useful for many I/O-bound workloads. :contentReference[oaicite:5]{index=5}
Important GIL lesson
Do not use the statement "Python threads do not work" as a rule. A better question is whether the workload spends most of its time executing Python code or waiting for external operations.
CPU-Bound vs I/O-Bound Workloads
| Workload | Examples | Typical Choice |
|---|---|---|
| I/O-bound | HTTP requests, file waits, sockets | Threading, ThreadPoolExecutor, asyncio |
| CPU-bound | Image processing, calculations, simulations | Multiprocessing, ProcessPoolExecutor, suitable parallel runtimes |
| Mixed | Fetch data, transform it, save results | Combination based on the actual bottleneck |
Python Multiprocessing
The
multiprocessing
module starts separate operating-system processes. Because each process has its own Python interpreter state, process-based execution can bypass the limitations of the GIL and use multiple CPU cores for CPU-bound work. :contentReference[oaicite:6]{index=6}
from multiprocessing import Process
def calculate_square(value):
print(
f"Square of {value}:",
value * value
)
if __name__ == "__main__":
process = Process(
target=calculate_square,
args=(10,)
)
process.start()
process.join()
The
if __name__ == "__main__"
guard is particularly important for portable multiprocessing code because worker processes may import the main module when using the
spawn
or
forkserver
start methods. :contentReference[oaicite:7]{index=7}
ProcessPoolExecutor
For many applications, the higher-level
ProcessPoolExecutor
API is more convenient than managing individual processes yourself. It provides the same general Future-based executor model used by
ThreadPoolExecutor,
while running work in separate processes. :contentReference[oaicite:8]{index=8}
from concurrent.futures import ProcessPoolExecutor
def calculate_square(value):
return value * value
if __name__ == "__main__":
values = [1, 2, 3, 4, 5]
with ProcessPoolExecutor(
max_workers=3
) as executor:
results = executor.map(
calculate_square,
values
)
print(list(results))
Process pools are useful when a large set of independent computations can be split across worker processes.
Data Transfer Between Processes
Threads share memory, but processes normally do not share ordinary Python objects directly. Arguments, return values, and task data often need to be serialized before being transferred between processes.
from concurrent.futures import ProcessPoolExecutor
def calculate(data):
return sum(data)
if __name__ == "__main__":
values = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
with ProcessPoolExecutor(
max_workers=3
) as executor:
results = executor.map(
calculate,
values
)
print(list(results))
Large amounts of data moving between processes can reduce the benefit of parallel computation. Process-based designs should therefore consider both computation cost and communication cost. Python's multiprocessing documentation explicitly recommends avoiding unnecessary movement of large amounts of data between processes. :contentReference[oaicite:9]{index=9}
Multiprocessing Start Methods
Process creation can use different start methods depending on the platform and Python version. Current Python 3.14 documentation lists
spawn,
fork,
and
forkserver.
In Python 3.14, the default changed away from
fork;
forkserver
became the default on supported POSIX platforms, while Windows and macOS use
spawn.
:contentReference[oaicite:10]{index=10}
import multiprocessing as mp
if __name__ == "__main__":
context = mp.get_context(
"spawn"
)
process = context.Process(
target=print,
args=("Hello from worker",)
)
process.start()
process.join()
When writing reusable libraries, avoid unnecessarily forcing one multiprocessing context on the application. A library should generally allow the surrounding application to choose the appropriate process model. :contentReference[oaicite:11]{index=11}
InterpreterPoolExecutor
Python 3.14 introduced
InterpreterPoolExecutor
in
concurrent.futures.
It uses worker threads where each thread runs tasks in its own interpreter. These interpreters have isolated runtime state and their own GIL, allowing true multi-core execution while remaining within one process. :contentReference[oaicite:12]{index=12}
from concurrent.futures import InterpreterPoolExecutor
def calculate(value):
return value * value
if __name__ == "__main__":
with InterpreterPoolExecutor(
max_workers=2
) as executor:
futures = [
executor.submit(
calculate,
value
)
for value in range(1, 6)
]
results = [
future.result()
for future in futures
]
print(results)
The isolation model is an important difference from ordinary threads: mutable Python objects are not freely shared between interpreters. Communication therefore requires explicit data transfer or dedicated mechanisms. :contentReference[oaicite:13]{index=13}
Free-Threaded Python
Modern CPython also supports optional free-threaded builds beginning with Python 3.13, where the GIL can be disabled. This allows threads to execute Python code in parallel across multiple CPU cores, although the ecosystem is still subject to compatibility considerations and not every third-party package necessarily supports free-threaded execution. :contentReference[oaicite:14]{index=14}
Do not generalize from free-threading
Free-threaded Python is an important development in Python concurrency, but you should still choose a concurrency model based on workload, library compatibility, memory sharing, complexity, and measured performance rather than assuming that threads are now the universal solution.
Shared State and Race Conditions
Threads operate in shared memory, which is convenient but creates the possibility of race conditions. A race condition occurs when the result depends on the timing of concurrent operations accessing shared state.
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
counter += 1
threads = [
threading.Thread(
target=increment
)
for _ in range(4)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter)
Shared state should not be modified concurrently without considering the synchronization guarantees of the program.
Protecting Shared State with Lock
A
threading.Lock
can protect a critical section so that only one thread enters that section at a time.
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(10000):
with lock:
counter += 1
threads = [
threading.Thread(
target=increment
)
for _ in range(4)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter)
The lock protects the shared update, preventing multiple threads from modifying the protected state simultaneously.
Lock vs RLock
A regular
Lock
can be acquired by one thread at a time. An
RLock
is reentrant, meaning the thread holding it can acquire it again without deadlocking itself. Reentrant locks are useful when nested code paths may need to enter the same lock-protected abstraction.
Producer-Consumer Queues
Queues are often a better communication mechanism than having multiple workers manipulate shared collections directly. The standard-library
queue
module provides thread-safe queues for communication between threads.
import queue
import threading
import time
jobs = queue.Queue()
def worker():
while True:
job = jobs.get()
try:
print(
f"Processing {job}"
)
time.sleep(1)
finally:
jobs.task_done()
thread = threading.Thread(
target=worker,
daemon=True
)
thread.start()
for job in range(5):
jobs.put(job)
jobs.join()
print("All jobs processed")
The queue separates producers from consumers and gives the application a clear handoff point between submitting and processing work.
Thread Synchronization Tools
| Tool | Purpose |
|---|---|
| Lock | Protect a critical section |
| RLock | Protect reentrant critical sections |
| Event | Signal that a state or condition is ready |
| Condition | Coordinate workers around a condition |
| Semaphore | Limit concurrent access to a resource |
| Queue | Exchange work safely between threads |
Avoid Shared State When Possible
Synchronization can make concurrent programs safe, but excessive shared mutable state makes them harder to understand. A design where workers receive input, perform work, and return results is often easier to reason about than a design in which every worker modifies several global objects.
def process_order(order):
return {
"id": order["id"],
"total": order["price"] * order["quantity"]
}
Independent input and output values reduce the amount of synchronization required.
ThreadPoolExecutor vs ProcessPoolExecutor
| Feature | ThreadPoolExecutor | ProcessPoolExecutor |
|---|---|---|
| Workers | Threads | Processes |
| Memory | Shared process memory | Separate process memory |
| Typical workload | I/O-bound | CPU-bound |
| GIL | Relevant in standard CPython builds | Bypassed through separate processes |
| Data sharing | Easy to share, but synchronization is required | Requires explicit inter-process communication |
Choosing the Right Concurrency Model
Start by identifying what your application spends most of its time doing.
Is the workload mostly waiting?
|
Yes
|
+----> High-level async architecture?
| |
| +----> asyncio
|
+----> Existing blocking APIs?
|
+----> ThreadPoolExecutor
Is the workload mostly CPU computation?
|
Yes
|
+----> ProcessPoolExecutor
|
+----> multiprocessing
|
+----> Other parallel execution strategy
This is a starting point, not an absolute rule. Measure real workloads because the cost of serialization, process startup, thread management, synchronization, and external services can change the best choice.
Combining Asyncio with Threads
Real applications sometimes need more than one concurrency model. An async web service may use asyncio for network operations while sending a legacy blocking operation to a thread.
import asyncio
import time
def legacy_operation():
time.sleep(2)
return "Legacy result"
async def handler():
result = await asyncio.to_thread(
legacy_operation
)
return result
asyncio.run(handler())
This kind of hybrid architecture can be useful when replacing a blocking dependency is not immediately practical, but the system still needs to keep its main asynchronous flow responsive.
Concurrency Does Not Automatically Mean Faster
Concurrent execution introduces overhead. Threads consume resources, processes require additional memory and communication, and synchronization can introduce contention. For a tiny task, running it concurrently may actually be slower than executing it directly.
Good concurrency design therefore starts with measurement. Benchmark the real workload rather than assuming that adding more workers will always improve throughput.
Too Many Workers Can Hurt Performance
Increasing the worker count indefinitely is usually a mistake. Too many workers can increase context switching, memory consumption, contention, connection pressure, and load on external systems.
with ThreadPoolExecutor(
max_workers=10
) as executor:
...
The appropriate number depends on the workload and system limits. Executor defaults have also evolved across Python releases, so application code should avoid assuming that a default worker count represents an application-specific optimal value. :contentReference[oaicite:15]{index=15}
Cancellation and Shutdown
Concurrent work needs a defined shutdown strategy. Applications may need to stop accepting new work, allow already-started operations to complete, cancel pending operations, or terminate workers during shutdown.
Context managers around executors provide a convenient lifecycle boundary for many applications. Process-based systems should also make sure child processes are correctly joined or otherwise managed rather than leaving unmanaged workers behind.
Deadlocks
A deadlock occurs when concurrent tasks wait indefinitely for resources held by each other.
Thread A:
Lock A
Wait for Lock B
Thread B:
Lock B
Wait for Lock A
Consistent lock ordering, smaller critical sections, and minimizing nested locks can reduce deadlock risk.
Thread Starvation and Contention
Even without a deadlock, one task can make poor progress because another task holds a required resource for too long. Long critical sections increase contention and reduce the benefits of concurrency.
Keep lock-protected operations as small as practical and avoid performing slow network requests or unrelated work while holding a shared lock.
Concurrency and Database Access
Database-heavy applications often benefit from concurrency because queries and network operations involve waiting. However, the database connection pool itself is a limited resource.
Launching hundreds of database operations concurrently does not necessarily improve performance. Worker counts should respect connection-pool capacity, database throughput, transaction behavior, and query cost.
Concurrency and External APIs
The same principle applies to HTTP APIs. Concurrent requests can improve throughput when requests are independent, but external services may enforce request limits.
Production API clients should therefore consider bounded concurrency, timeouts, retries for appropriate transient failures, and backoff rather than simply launching an unlimited number of requests.
Testing Concurrent Code
Concurrent code can fail intermittently because timing changes from run to run. Tests should avoid relying on arbitrary sleeps whenever possible.
Prefer synchronization primitives, controlled test doubles, deterministic queues, explicit events, and clearly defined worker lifecycles. Test both successful execution and failure conditions such as worker exceptions, cancellation, and shutdown.
Logging Concurrent Applications
Logs become especially important when several workers are operating at the same time. Include identifiers such as task IDs, job IDs, or request IDs where appropriate so individual operations can be traced across concurrent execution.
import logging
import threading
logger = logging.getLogger(__name__)
def process_job(job_id):
logger.info(
"Thread=%s processing job=%s",
threading.current_thread().name,
job_id
)
A Practical Worker Pool Example
The following example represents a common production-style pattern: a known set of jobs is processed using a bounded pool, and results are collected through Futures.
from concurrent.futures import (
ThreadPoolExecutor,
as_completed
)
import time
def process_job(job):
job_id = job["id"]
time.sleep(1)
return {
"id": job_id,
"status": "completed"
}
jobs = [
{"id": 101},
{"id": 102},
{"id": 103},
{"id": 104},
{"id": 105}
]
with ThreadPoolExecutor(
max_workers=3
) as executor:
futures = {
executor.submit(
process_job,
job
): job["id"]
for job in jobs
}
for future in as_completed(futures):
job_id = futures[future]
try:
result = future.result()
print(
f"Job {job_id}: {result}"
)
except Exception as exc:
print(
f"Job {job_id} failed: {exc}"
)
The mapping between each Future and its job ID is useful because concurrent results may finish in a different order from the order in which work was submitted.
Common Concurrency Mistakes
Using Threads for Every Problem
Threads are useful, but CPU-heavy pure-Python workloads may not benefit from standard CPython threads because of the GIL.
Ignoring Shared State
Concurrent access to mutable state can introduce race conditions, inconsistent data, and difficult-to-reproduce bugs.
Creating Too Many Workers
An unnecessarily large worker pool can increase overhead and overload databases, APIs, filesystems, or other shared resources.
Holding Locks Too Long
Large critical sections reduce concurrency and increase contention between workers.
Passing Huge Objects to Processes
Process pools often need to serialize task arguments and results, so excessive data transfer can erase the benefit of parallel computation.
Assuming Concurrent Means Faster
Worker management, communication, synchronization, and contention all have costs. Measure the actual workload before and after concurrency changes.
Best Practices for Python Concurrency
- Identify whether the workload is CPU-bound, I/O-bound, or mixed before choosing a model.
- Prefer ThreadPoolExecutor for simple concurrent I/O workloads that use blocking APIs.
- Prefer ProcessPoolExecutor or multiprocessing for suitable CPU-bound work in standard CPython builds.
- Use asyncio when the application is designed around asynchronous I/O.
- Keep shared mutable state to a minimum.
- Use locks and synchronization primitives around genuinely shared state.
- Prefer queues for producer-consumer communication.
- Keep critical sections small.
- Limit concurrency according to real system constraints.
- Do not send unnecessarily large amounts of data between processes.
- Handle Future exceptions explicitly.
- Define worker startup and shutdown behavior clearly.
- Use logging that allows concurrent operations to be traced.
- Benchmark before deciding that one concurrency model is better than another.
- Consider newer options such as free-threaded CPython and InterpreterPoolExecutor only when their compatibility and isolation trade-offs fit the application. :contentReference[oaicite:16]{index=16}
Concurrency Decision Guide
Ask these questions before implementing concurrency
- What is the expensive part of the workload?
- Is the program primarily waiting or calculating?
- Does the library I am using support asynchronous I/O?
- Does the work need shared mutable state?
- Can the jobs be processed independently?
- How much data must move between workers?
- What are the limits of the external system?
- How will errors and cancellation be handled?
- How will the application shut workers down safely?
- What does benchmarking say about the actual bottleneck?
Concurrency vs Asyncio
Asyncio deserves special attention because it also provides concurrency, but through an event-loop-based model rather than multiple ordinary worker threads.
| Question | Thread/Process Pools | asyncio |
|---|---|---|
| Execution model | Threads or processes | Event loop and tasks |
| Blocking APIs | Natural fit for threads | Need async APIs or an appropriate bridge |
| CPU parallelism | Processes can provide it | Not provided by ordinary event-loop tasks |
| Shared state | Threads share; processes isolate | Usually shared within the event-loop thread |
Do Not Mix Models Without a Reason
Combining asyncio, threads, and processes can be powerful, but every additional concurrency model introduces another lifecycle and failure boundary. Use a hybrid design when the workload genuinely requires it, not simply because every model is available.
For example, an application may use asyncio for high-volume network traffic, a small thread pool for a legacy blocking library, and a process pool for expensive CPU transformations. Each model then has a clear responsibility.
Summary
Python concurrency is about choosing the right way to overlap work. Threads are useful for many I/O-bound workloads, processes are useful for suitable CPU-bound workloads, executor pools simplify worker management, and asyncio provides task-level concurrency around asynchronous I/O.
The GIL is an important consideration for standard CPython builds, but it should not be treated as a complete explanation of Python concurrency. Modern Python also includes optional free-threaded builds and isolated interpreter-based concurrency, while process-based and asynchronous models remain important for production systems. :contentReference[oaicite:17]{index=17}
Good concurrent code is not simply code with more workers. It defines clear ownership of state, limits resource usage, handles errors, avoids deadlocks, manages worker lifetimes, and is validated through measurement. Start with a simple design, understand the actual bottleneck, and introduce concurrency only where it improves the system.
Interview Questions to Prepare
- What is the difference between concurrency and parallelism?
- What is the Global Interpreter Lock?
- Why are Python threads useful for I/O-bound workloads?
- Why are processes often preferred for CPU-bound pure-Python workloads?
- What is ThreadPoolExecutor?
- What is ProcessPoolExecutor?
- What is a Future?
- What is the difference between submit(), map(), and as_completed()?
- What causes a race condition?
- How does threading.Lock prevent unsafe shared-state updates?
- Why are queues useful in concurrent applications?
- Why can passing large objects to ProcessPoolExecutor be expensive?
- Why is if __name__ == "__main__" important in multiprocessing applications?
- What changed about multiprocessing start methods in Python 3.14?
- What is InterpreterPoolExecutor?
- What is free-threaded Python?
- When would you choose asyncio instead of ThreadPoolExecutor?