- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Concurrency
Python Concurrency: Threads, Processes and asyncio
threading, multiprocessing, concurrent.futures and asyncio with async and await, find and fix race conditions, handle errors, timeouts and cancellation, and measure whether the concurrent version is really faster and still correct.IntermediateLesson 9 of 9 in Intermediate Python Course
What you will learn
- Tell concurrency from parallelism, decide whether a task is I/O-bound or CPU-bound, and explain how the global interpreter lock and free-threaded builds change what threads can speed up.
- Tell concurrency from parallelism and classify workloadsUse the two terms in their standard meanings, classify a task as I/O-bound or CPU-bound, and predict when overlapping tasks can save time.
- Explain the global interpreter lock and free-threaded buildsDescribe what the GIL does and does not protect, why threads still help I/O-bound work, and how a free-threaded build differs from the standard one.
- Tell concurrency from parallelism and classify workloads
- Start and coordinate threads with the
threadingmodule, protect shared data from race conditions with locks, and pass work safely between threads with queues and events.- Start threads, wait for them and collect their resultsCreate threads with
threading.Thread, run them at the same time, wait withjoin(), and collect results and errors correctly. - Find and fix race conditions with locksRecognize the interleavings that cause race conditions in shared data, and protect critical sections with
threading.Lockwithout losing the benefit of concurrency. - Pass work between threads with queues and eventsOrganize threads as producers and consumers around a thread-safe
queue.Queue, stop them cleanly with sentinels or anEvent, and limit simultaneous access with a semaphore.
- Start threads, wait for them and collect their results
- Run CPU-bound work in parallel with the
multiprocessingmodule, write programs that start processes safely on every platform, and move data between processes without shared-state bugs.- Start processes safely with multiprocessingCreate and join processes, guard the main module, know the start methods and their platform defaults, and keep functions and data picklable.
- Share data and results between processesMove data between processes with queues and pools, use shared values with their locks when state must be shared, and design CPU work as independent chunks combined at the end.
- Start processes safely with multiprocessing
- Submit work to thread and process pools, read results through futures, handle errors, timeouts and cancellation, and configure pools for the workload.
- Submit tasks and read their futuresUse
ThreadPoolExecutorandProcessPoolExecutorwithsubmit()andmap(), and read results, errors and status fromFutureobjects. - Process results as they finish and handle errors and timeoutsRead results in completion order with
as_completed(), wait selectively withwait(), and handle failures, timeouts, cancellation and broken pools. - Configure thread, process and interpreter poolsChoose the executor class for the work, set worker counts and batch sizes, prepare each worker once, and know what the newer interpreter pool offers.
- Submit tasks and read their futures
- Define and run coroutines with
asyncandawait, run many tasks concurrently in one thread, handle timeouts, cancellation and errors, and keep the event loop free of blocking work.- Define and run coroutines with async and awaitExplain how the event loop runs coroutines cooperatively, write
async deffunctions, await results and start a program withasyncio.run(). - Run tasks concurrently with gather and TaskGroupSchedule coroutines as tasks, run them together with
asyncio.gather()andasyncio.TaskGroup, and predict their results, timing and behavior when one fails. - Handle timeouts, cancellation and errors in async codePut time limits on awaits with
asyncio.timeout()andasyncio.wait_for(), cancel tasks and clean up correctly, and avoid losing errors in background tasks. - Keep the event loop responsive and protect shared stateRecognize blocking calls in async code, move blocking or CPU-heavy work off the event loop, limit how many tasks run at once, and prevent races between tasks.
- Define and run coroutines with async and await
- Choose threads, processes or asyncio from the nature of a workload, combine them where a program needs more than one, and measure whether the concurrent version is faster and still correct.
- Choose a concurrency model for a workloadFollow a clear sequence of questions to pick threads, processes, asyncio or no concurrency, and justify the choice with the trade-offs of each model.
- Measure speedup, overhead and correctnessTime sequential and concurrent versions fairly, compute speedup and efficiency, estimate the limit with Amdahl's law, and confirm that the concurrent version gives the same results.
- Choose a concurrency model for a workload
Python Concurrency study guide
1Explain how concurrency works in Python
Waiting and computing create different opportunities for concurrency. Use timelines and simple measurements to find the time a program can save, then connect that finding to threads, processes, and asyncio. CPython's interpreter build also matters: the global interpreter lock limits bytecode execution in standard builds, while a free-threaded build permits a different kind of scaling. Shared program state still needs careful coordination in either build.
1.1 Find the time that concurrency can save
A program can have several jobs under way even when only one job is computing. Concurrency means their lifetimes overlap. Parallelism means computations happen at the same instant on different cores. Taking turns on one core gives concurrency; using several cores can also give parallelism.
Look for waiting or computing
An I/O-bound job spends much of its time waiting for a network, disk, database, timer, or user. During a wait, another job can run. A CPU-bound job spends much of its time calculating. Taking turns on one core cannot remove that calculation time.
Think of one cook heating water while chopping vegetables. Both jobs are in progress, but the cook performs one hands-on action at a time. Two cooks chopping simultaneously add parallelism. Rob Pike's distinction between organizing many activities and executing them simultaneously captures this difference.
Measure a sequential run with two clocks:
import time
wall_start = time.perf_counter()
cpu_start = time.process_time()
result = run_job()
cpu_seconds = time.process_time() - cpu_start
wall_seconds = time.perf_counter() - wall_start
run_job() stands for the function being measured. The wall clock includes waiting. The CPU clock counts computation used by this process. A download job taking 20 s of wall time and 0.4 s of CPU time spends most of its time waiting. Similar wall and CPU times point toward computation in a single-threaded sequential job. Measure before splitting the work: the slow part may differ from the part that looks complicated.
Work through two timelines
Ten independent downloads each wait 0.5 s. Sequentially, their waits add:
With ten overlapping waits, the batch takes about 0.5 s plus startup and processing overhead. A single core can achieve this because the downloads spend their time waiting.
Now consider four independent calculations, each requiring about 2 s of CPU work. One core must still perform about 8 s of computation, even if it switches among four jobs. Four free cores can complete the calculations in about 2 s plus worker and data-transfer costs.
Match the model to the bottleneck
| Model | Where work runs | Main use in standard CPython |
|---|---|---|
| Threads | Several execution paths sharing one process | Overlapping blocking I/O |
| Processes | Separate interpreters with separate memory | Parallel pure-Python computation |
| asyncio | Tasks taking turns in one thread | Many waits through async libraries |
concurrent.futures supplies a common pool interface for threads and processes. A pool reuses workers across jobs.
A downloader that also parses large documents has two stages: network waiting and computation. Time them separately. More workers add costs and only help when work can proceed independently, waiting can overlap, or free cores can compute. For a job already finishing in 0.01 s, worker startup may cost more than the work saved.
Key Takeaways
- Concurrency overlaps task lifetimes; parallelism executes computations simultaneously.
- Compare wall time with CPU time in a sequential run to locate waiting.
- Overlap independent I/O waits; use additional cores for independent CPU work.
- Worker startup, switching, and data transfer count toward the total time.
1.2 Understand what the GIL protects
CPython is the usual implementation of Python. Its standard build has a global interpreter lock, or GIL: within one interpreter, only one thread executes Python bytecode at a time. This protects interpreter internals, including memory-management state. It does not protect the rules your program must preserve.
Why threads can still help
Four threads executing pure-Python calculations take turns holding the GIL. They cannot spread that bytecode execution across four cores in the standard build. Switching may make the threaded version slower.
A thread releases the GIL during blocking operations such as socket reads and time.sleep(). Other threads can run while it waits. Some compiled extensions also release it during expensive work. Large-data hashing in hashlib, compression in zlib, and many NumPy operations can therefore benefit from threads even when the job is computational.
The default requested switch interval is 0.005 s, or 5 ms. Inspect it with sys.getswitchinterval(). It is not a promise that a switch occurs every 5 ms or at a particular source line.
Consider two threads updating a shared count. One reads the old value, another updates it, and the first writes a value based on its stale read. The interpreter can remain internally sound while the program loses an update. Protect shared read-modify-write or check-then-act sequences with a shared lock.
Recognize a free-threaded build
A free-threaded build allows Python threads to compute simultaneously on several cores when the GIL is disabled. It was experimental in Python 3.13 and became supported in 3.14. It remains a separate build; installing a newer standard interpreter does not remove its GIL.
import sys
import sysconfig
print(sysconfig.get_config_var("Py_GIL_DISABLED"))
# Python 3.13 and later:
print(sys._is_gil_enabled())
The first check reports build capability: 1 means the build supports free threading. The second reports the current runtime state: True means the GIL is active. python -VV also identifies a free-threading build. Its executable often has a t suffix, such as python3.14t.
Check the running environment
A capable build can run with the GIL enabled. PYTHON_GIL=1 or -X gil=1 requests this. Importing a C extension that lacks free-threading support can also enable the GIL and produce a warning. Record runtime state after importing the libraries a benchmark uses.
Free threading needs more memory and can slow single-threaded work. Python's published benchmarks report roughly 1%–8% single-thread overhead, depending on platform. Package compatibility also matters. Built-in containers use internal protection, but a sequence such as checking whether a key exists and then inserting it still needs coordination.
| Execution setting | Pure-Python CPU threads |
|---|---|
| Standard build with GIL | Take turns executing bytecode |
| Free-threaded build with GIL disabled | Can execute on several cores |
Removing the GIL increases the opportunities for conflicting shared updates. Keep locks around logical transactions, or give workers separate data and combine their results afterward.
Key Takeaways
- The GIL restricts Python bytecode execution within one CPython interpreter.
- Blocking I/O and some compiled operations release the GIL.
- The GIL does not make shared multi-step program operations safe.
- Free-threading capability and the current GIL state are separate checks.
- Free-threaded execution requires compatible packages and correct synchronization.
2Run I/O-bound tasks with threads
Threads let independent blocking operations make progress together inside one process. Their shared memory makes it easy to exchange values, but it also makes conflicting updates possible. Build a clear worker lifetime, collect outcomes explicitly, and trace the reads and writes that need protection. Queues, events, and semaphores then let a small set of workers handle a stream of jobs and shut down cleanly.
2.1 Start threads before waiting for results
A thread has its own call stack but shares its process's objects with other threads. The main thread starts with the program. Additional threads can overlap blocking waits while the main thread coordinates their work.
Pass a function, then start it
import threading
import time
results = [None] * 3
def read_item(index, name):
time.sleep(0.5)
results[index] = name.upper()
names = ["oak", "elm", "ash"]
threads = [
threading.Thread(target=read_item, args=(i, name))
for i, name in enumerate(names)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(results)
Creating a Thread object prepares it. start() runs the target in a new thread; join() waits in the calling thread. The result is ['OAK', 'ELM', 'ASH']. Each worker writes a separate preassigned slot, and the main thread reads after all joins. The three waits overlap, so the sleep portion takes about 0.5 s.
Keep starting and joining in separate loops. Starting one thread and joining it immediately would finish that job before starting the next. Call start() only once per object; create a new object for a new run.
Pass target=read_item, not target=read_item(i, name). The latter calls the function immediately in the main thread and passes its return value as the target. Arguments belong in args or kwargs.
For one argument, write args=(name,). The comma makes a one-item tuple. args=("abc") is just a string, so Python unpacks three characters as three positional arguments.
Collect values and failures deliberately
A raw thread discards its target's return value, and join() returns None. Use preassigned result slots, a thread-safe queue, or an executor future to carry values back.
An uncaught worker exception normally prints a traceback through threading.excepthook and ends that thread. It does not reappear in the main thread when join() returns. If a missing result matters, catch the error in the worker and report it through a queue, or use ThreadPoolExecutor so reading the future re-raises it.
A timeout limits the wait, not the worker:
thread.join(timeout=2.0)
if thread.is_alive():
print("still running")
Both a completed join and a timed-out join return None. is_alive() supplies the distinction.
Finish background work cleanly
A non-daemon thread keeps the process alive. Python exits when only daemon threads remain; those threads may stop abruptly without flushing files or finishing cleanup. Set daemon=True before starting only for helpers whose unfinished work may be lost. For required work, signal a cooperative stop with an Event, then join the workers so they can release resources.
Key Takeaways
- Pass the target function object and its arguments separately.
- Start every worker before joining workers whose waits should overlap.
- Use result slots, queues, or futures to collect values and failures.
- After a timed join, use
is_alive()to check whether work continues. - Use cooperative shutdown and joins for work that must finish.
2.2 Protect the whole shared update
A race condition makes a result depend on how shared accesses interleave. The danger appears when several threads access mutable data, at least one writes, and they do not coordinate the accesses that belong together.
Trace a lost update
Suppose count starts at 41 and two threads each add one:
- Thread A reads 41.
- Thread B reads 41 and stores 42.
- Thread A resumes and stores its own calculated 42.
The expected result is 43. Both updates used the same old value, so one was lost. A read, calculation, and write form a logical operation even when written as count += 1. A correct total on one run gives no guarantee about the next interleaving.
A check-then-act race is similar. With a balance of 100, two threads can both pass if balance >= 80 before either subtracts 80. If both withdrawals then occur, the balance is -60. Locking only the subtraction leaves the decision based on stale information.
Share one lock
A critical section is the part that must run without a conflicting access from another worker. Make one lock for the shared data and use it in every conflicting path:
import threading
balance = 100
balance_lock = threading.Lock()
def withdraw(amount):
global balance
with balance_lock:
if balance >= amount:
balance -= amount
return True
return False
If two threads call withdraw(80), the first lock holder can succeed and leave 20. The next sees 20 and fails. The decision and update use one protected view of the balance.
The with block releases the lock even if an exception leaves it. Manual acquire() and release() need try/finally to give that protection. Creating a new lock inside each function call fails: different locks do not exclude one another.
Keep waiting outside the lock
Do downloads and expensive calculations before acquiring a result lock. Hold it only while changing the shared total or collection. If every worker holds the same lock during a 0.5 s download, the waits become sequential.
For a demonstration, split an increment into current = balance, time.sleep(0), and balance = current + 1. Two workers doing this 1,000 times each may produce 1,000, 1,385, or even the expected 2,000. A shared lock around the full sequence makes the total reliable. The sleep exposes an interleaving; adding sleeps is not a repair.
Avoid waiting on yourself
A Lock is not reentrant: trying to acquire it again while already holding it blocks. An RLock lets its owning thread acquire it repeatedly, with a matching release for every acquisition. If code needs two locks, acquire them in one consistent order across all threads.
An even simpler design gives each worker private input and returns a partial result. One thread combines the results at the end. Read-only objects need no lock for competing writes because there are no writes to coordinate.
Key Takeaways
- Trace reads and writes to find lost updates and stale checks.
- Protect the check and the change with the same shared lock.
- Use
with lock:so exceptions still release the lock. - Keep slow I/O outside short critical sections.
- Use a consistent lock order; use
RLockfor required same-thread reacquisition. - Independent worker results can remove the need for shared updates.
2.3 Coordinate workers with queues and signals
A producer-consumer design separates supplying work from doing it. Producers add items to a queue; a fixed group of workers removes them. queue.Queue handles its own synchronization, so threads can safely call put() and get() without adding a lock around those methods.
Account for each item
get() waits when the queue is empty. After processing an item, a worker calls task_done(). Queue join() waits for every submitted item to receive this acknowledgment; it does not join the worker threads.
import queue
import threading
jobs = queue.Queue(maxsize=100)
outputs = queue.Queue()
def worker():
while True:
item = jobs.get()
try:
if item is None:
return
outputs.put(item.upper())
finally:
jobs.task_done()
workers = [threading.Thread(target=worker) for _ in range(3)]
for thread in workers:
thread.start()
for name in ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt", "f.txt"]:
jobs.put(name)
for _ in workers:
jobs.put(None)
jobs.join()
for thread in workers:
thread.join()
results = [outputs.get() for _ in range(6)]
Here None is a sentinel, a value reserved to mean stop. Three workers need three sentinels. Each sentinel also needs task_done(), supplied by finally. The output names are uppercase, but their order can vary because workers finish independently.
This worker's string operation has a predictable input type. When real processing can fail, catch and report each item's error as well; acknowledging an item records that it was handled, not that processing succeeded.
Bound the backlog
With maxsize=100, put() waits while 100 items are queued. This backpressure slows a producer when workers fall behind and bounds the waiting backlog. It does not mean 100 items are executing at once; the worker count controls that.
Do not spin on empty() or treat qsize() as a guarantee. Another thread can change the queue immediately after the check. Use get() to wait efficiently, or get(timeout=1.0) and catch queue.Empty when a timed wait is useful. Python 3.13+ also supports shutdown(): after normal shutdown drains the queue, get() raises queue.ShutDown.
Choose the right signal
A threading.Event holds a flag: set() signals it, clear() resets it, and is_set() reads it. stop.wait(1.0) pauses until the signal or a one-second timeout. A worker can check the flag between jobs. Setting it does not interrupt an unrelated blocking get(); use sentinels or a timed queue wait to let that worker exit.
A threading.Semaphore(3) permits three simultaneous entries into with sem:. It limits active connections or another scarce resource. A lock protects a logical update; a semaphore allows a chosen number of concurrent operations.
Use a process queue between processes. Use asyncio.Queue with awaited operations between tasks in one event loop; that queue is not thread-safe.
Key Takeaways
- A queue transfers work safely between producers and consumers.
- Pair every retrieved item, including a sentinel, with one
task_done(). - Queue
join()tracks acknowledgments; threadjoin()waits for thread exit. - Send one stop sentinel per worker.
- Bound a queue to apply backpressure; use a semaphore to limit active work.
- An event signals cooperative shutdown but cannot interrupt any blocking operation.
3Use processes for CPU-bound work
Independent calculations can use several cores by running in separate Python processes. Separate memory changes how inputs and results move: a child cannot update the parent's normal list, and startup can import the main module again. Build script entry points that work with spawn and forkserver, then divide work into chunks whose returned results can be combined without a shared counter.
3.1 Start a process from an importable script
A process has its own interpreter and memory. Separate standard CPython processes have separate GILs, so independent calculations can execute on different cores. Ordinary objects do not become shared simply because both processes use the same variable name.
Make the entry point safe
Run this as a script:
import multiprocessing as mp
def compute(n):
print(sum(i * i for i in range(n)))
if __name__ == "__main__":
ctx = mp.get_context("spawn")
process = ctx.Process(target=compute, args=(10,))
process.start()
process.join()
print("exit:", process.exitcode)
The worker prints 285, and a normal finish gives exit code 0. An uncaught exception ordinarily gives 1; on POSIX a negative exit code indicates termination by a signal. join() waits but does not return the function's value.
The target is defined at module level so a child can import it. Starting the process sits under the main-module guard. With spawn, a child imports the main module in a fresh interpreter. The guard prevents that import from starting another round of children. Without it, Python can raise a bootstrapping RuntimeError.
Know what the child starts from
| Method | How the child starts | Usual platform default |
|---|---|---|
spawn | New interpreter importing the main module | Windows and macOS |
fork | Copy of the parent process | No platform since Python 3.14 |
forkserver | Fork requested from a separate server | Linux in Python 3.14+ |
Linux used fork before 3.14. Forkserver is available on POSIX systems with the required facilities. Its server normally imports the main module once, and children inherit the server's state, not the parent's later global changes. Spawn also does not see later changes just because they happened in the parent. Pass required inputs explicitly.
get_context("spawn") selects a method directly. Forking an already multithreaded process is unsafe; Python 3.12+ can issue a DeprecationWarning when it detects this situation.
Pass data the child can receive
Spawn and forkserver serialize process targets and arguments with pickle. Queue messages and pool calls are pickled with every start method. A raw forked Process inherits its target and arguments instead.
Use importable top-level functions and plain data. Lambdas, nested functions, open file objects, most database connections, and threading.Lock objects cannot be passed where ordinary pickling is required. A function defined only at an interactive prompt also cannot be imported by a spawned child. Use a script for process-based examples.
Starting interpreters and moving data cost time. Give each process substantial independent work and start with about one worker per usable core. Python 3.13+ provides os.process_cpu_count() for that count; allow for a missing count when choosing a fallback.
Key Takeaways
- Processes provide separate interpreters and memory for CPU parallelism.
- Keep targets importable and guard process startup in a script.
- Spawn imports afresh; forkserver children inherit the server, not later parent state.
- Pool calls and queue messages must be picklable under every start method.
- Use substantial jobs and choose worker counts from usable cores.
3.2 Return partial results instead of sharing updates
When a child appends to a normal global list, it changes its own memory. The parent's list remains unchanged after join(). Move results explicitly through a process-safe channel or return them from a pool call.
Split, compute, combine
A fixed pool reuses worker processes. Each worker receives a self-contained input and returns a partial result:
from multiprocessing import get_context
def sum_squares(bounds):
start, stop = bounds
return sum(i * i for i in range(start, stop))
if __name__ == "__main__":
chunks = [(0, 5), (5, 10)]
with get_context("spawn").Pool(2) as pool:
partials = pool.map(sum_squares, chunks)
print(partials, sum(partials))
The intervals include their start and exclude their stop. The partials are 30 and 255; the total is 285. Each number is counted once. The parent combines the returned values, so the workers need no shared counter.
For a larger example, count primes in four consecutive half-million intervals below 2,000,000. The partial counts are 41,538, 36,960, 35,657, and 34,778. Adding them gives 148,933. The same split-compute-combine structure works as long as the chunks cover the intended inputs exactly once.
Pool.map() returns a list in input order. imap_unordered() supplies results as jobs finish. apply_async() submits one call and returns a handle whose get() retrieves the value or error. ProcessPoolExecutor offers futures for the same independent-call pattern.
Keep messages small
multiprocessing.Queue offers put() and get() across processes; each object is pickled in transit. Pipe() gives two endpoints with send() and recv(). Receive queue output before joining the producer: a child sending a large payload may need the parent to drain the queue before it can finish.
Send a range, file name, or other small description when possible. Repeatedly copying a 500 MB list can overwhelm useful computation. An initializer loads common data once per worker; alternatively, workers can read their own portions from disk.
Share state only when it is needed
Value('i', 0) holds a shared C integer, and Array('d', 10) holds ten shared C doubles. Shared storage does not make a compound update atomic:
with counter.get_lock():
counter.value += 1
The value's lock covers both reading and writing. Locking an individual read and an individual write separately would still leave room for a lost update between them.
A Manager runs a server process that owns objects such as lists and dictionaries. Workers use proxies to send operations to it. This is flexible but slower than direct shared memory because accesses require messages. A multi-operation decision still needs coordination. Prefer returned partial values when one final total is all the parent needs.
Key Takeaways
- Ordinary child changes do not update the parent's objects.
- Split inputs without gaps or overlaps and combine returned partial results.
- Pickling and copying make message size part of the performance cost.
- Drain process queue output before joining a producer that may still be flushing it.
- A shared
Valuestill needs its lock for read-modify-write updates. - Manager proxies trade flexibility for message overhead.
4Run tasks with concurrent.futures executors
An executor handles worker reuse so the program can focus on submitted calls and their outcomes. Futures separate scheduling from waiting, while completion-order reading makes finished results available promptly. Error handling, deadlines, and cancellation each need a clear meaning. Pool size, process startup, batch size, and one-time setup then determine how much useful work the workers can perform.
4.1 Submit work and keep its future
An executor manages reusable workers. ThreadPoolExecutor uses threads; ProcessPoolExecutor uses processes. Both accept calls and return objects that let the caller retrieve their eventual results.
Separate submission from waiting
from concurrent.futures import ThreadPoolExecutor
import time
def read_name(name):
time.sleep(0.5)
return name.upper()
with ThreadPoolExecutor(max_workers=3) as executor:
futures = [executor.submit(read_name, name)
for name in ["oak", "elm", "ash"]]
results = [future.result() for future in futures]
print(results)
submit(read_name, name) schedules a call and immediately returns a future. A future represents an outcome that may not be ready yet. All three calls are submitted before any result is requested, so their waits overlap. Reading futures in submission order still allows concurrency because they are already scheduled.
Calling executor.submit(read_name, name).result() inside the submission loop would wait for each call before submitting the next. Also pass read_name itself; submit(read_name(name)) runs the call immediately in the caller.
Leaving the executor's with block calls shutdown(wait=True), waiting for submitted work. After shutdown, new submissions raise RuntimeError. This structure gives the workers a clear lifetime.
Read the outcome, including errors
future.result() waits for completion, then returns the worker's value or re-raises its exception. done() reports whether the call finished or was cancelled. For a completed, non-cancelled future, exception() returns its exception or None. Calling exception() before completion can wait too. cancel() succeeds only while cancellation is still possible before execution starts.
A task's exception stays in its future. It does not automatically stop other submitted work. If no code reads the failed future, the program can miss a failure even though its pool shuts down normally.
Use map when input order matters
executor.map(func, items) returns an iterator in input order, even when calls finish in a different order. In a thread pool:
values = executor.map(lambda x: 10 / x, [5, 2, 0, 1])
Reading yields 2.0, then 5.0, then raises ZeroDivisionError. Iteration does not proceed to the last result. For independent per-item error reporting, submit separate futures and handle each result.
Ten 0.5 s tasks need two rounds with five workers, taking about 1 s, or one round with ten workers, taking about 0.5 s. More workers than tasks cannot overlap additional waits.
Since Python 3.13, the default thread pool size is min(32, (os.process_cpu_count() or 1) + 4): eight usable cores give twelve threads. Python 3.8–3.12 used os.cpu_count() in that formula. Since Python 3.13, process pools default to the usable core count, with at most 61 workers on Windows; earlier versions used os.cpu_count(). Explicit settings make examples and limits easier to reason about.
Key Takeaways
- An executor reuses workers; a future represents one call's outcome.
- Submit independent calls before waiting on their results.
result()retrieves the return value or raises the worker's exception.map()preserves input order, even when completion order differs.- Leaving an executor context waits for submitted work.
4.2 Handle each result as soon as it is ready
Waiting in input order can delay useful results behind a slow first job. Completion order lets the program report finished work while other calls continue.
Keep the input attached to its future
from concurrent.futures import ThreadPoolExecutor, as_completed
def convert(text):
if not text:
raise ValueError("empty text")
return text.upper()
with ThreadPoolExecutor(max_workers=3) as executor:
sources = {executor.submit(convert, text): text
for text in ["oak", "", "elm"]}
for future in as_completed(sources):
text = sources[future]
try:
value = future.result()
except Exception as error:
print(f"{text!r} failed: {error}")
else:
print(f"{text!r}: {value}")
as_completed() yields completed futures. It does not extract their values, so call result() inside the loop. The dictionary recovers the input even if tasks finish in a different order. The local error handler lets successful calls be processed after a failure.
For three independent waits of 0.6 s, 0.2 s, and 0.4 s submitted in that order, three workers finish them at about 0.2 s, 0.4 s, and 0.6 s. map() would hold its first result until about 0.6 s because it preserves input order.
Wait for a condition
wait(futures, return_when=FIRST_COMPLETED) returns two sets: done and not_done. The sets have no promised ordering. FIRST_EXCEPTION returns after a failure, or after all finish if none fails. ALL_COMPLETED waits for all. Inspect the returned futures; returning from wait() does not cancel the unfinished ones.
Distinguish a deadline from stopping work
future.result(timeout=2) waits up to two seconds for the outcome and raises TimeoutError if it is not ready. The worker keeps running. In Python 3.11+, the futures timeout exception is the built-in TimeoutError.
An executor context still waits on exit. Catching a result timeout inside the context therefore does not make the whole program return at that deadline. Give the blocking network or database operation its own timeout when the operation itself must be bounded.
future.cancel() returns False once a call is running or finished. A successfully cancelled future raises CancelledError when its result is requested. shutdown(cancel_futures=True) in Python 3.9+ cancels eligible pending calls; it does not stop running calls.
Notice a failed pool
An abruptly terminated process worker can make the pool unusable. Pending futures raise BrokenProcessPool, and new submissions fail. Create a new pool to continue. Python 3.15 adds the dead process's ID and exit code to this diagnostic.
add_done_callback(fn) calls fn(future) after completion or cancellation, immediately if already done. Callback errors are logged and ignored. Keep essential result and error handling in the code that retrieves outcomes.
Key Takeaways
as_completed()yields futures in completion order; retrieve each outcome.- Map futures to their inputs for reliable per-item reporting.
wait()partitions futures without cancelling unfinished work.- A result timeout ends a wait, and context exit can still wait for the worker.
- Cancellation cannot stop an already running executor call.
- An abruptly lost process worker can break the entire pool.
4.3 Choose workers and reduce transfer costs
Choose a pool from the work it must perform. Blocking I/O suits a thread pool. Pure-Python computation in standard CPython suits a process pool. Changing the executor class keeps the submission interface similar, but changes memory, startup, and serialization requirements.
Prepare process calls for import and pickling
from concurrent.futures import ProcessPoolExecutor
import multiprocessing as mp
def square(n):
return n * n
if __name__ == "__main__":
with ProcessPoolExecutor(
max_workers=2,
mp_context=mp.get_context("spawn"),
) as executor:
values = list(executor.map(square, range(10), chunksize=4))
print(sum(values))
Run this as a script. The top-level function can be imported by workers, and the guard prevents process startup during import. Each function call, argument, and result crosses a serialization boundary. Replacing square with a lambda would fail ordinary pickling. Selecting fork does not remove a process pool's pickling requirement.
Batch small work
chunksize groups process-map inputs into batches. For 1,000,000 inputs, a size of 10,000 produces 100 batches instead of 1,000,000 one-item batches. Fewer messages can make small calls worth distributing. Batching does not remove the computation or the need to serialize the data.
A large batch can also leave a worker busy while another has no remaining batch to take. Measure the complete job with useful batch sizes. chunksize does not change a thread pool's work distribution.
Reuse setup and choose limits
Use initializer and initargs for setup performed once when each worker starts. For example, each process can load a lookup table once; each thread can open its own database connection. This avoids paying the setup cost on every task.
Start with about one process per usable core for CPU work. Extra CPU workers compete for the same cores and increase memory and switching costs. I/O threads may outnumber cores because most wait, but server limits, bandwidth, and memory still cap useful concurrency. Respect published service limits and adjust when requests receive errors such as HTTP 429.
max_tasks_per_child=100 in Python 3.11+ replaces a process after 100 tasks, helping contain growing worker memory. It is incompatible with fork; explicitly choosing spawn is a compatible combination.
Know the newer alternative
InterpreterPoolExecutor, added in Python 3.14, runs workers in isolated interpreters within one process. Each has its own GIL, enabling parallel Python execution. Calls still cross a pickle boundary, mutable objects are not ordinary shared thread data, and extension compatibility must be checked.
Before creating more workers, consider doing less work. A better algorithm or a compiled library can save more time than scheduling the same expensive Python loop across workers. Compiled operations that release the GIL can also make a thread pool useful for CPU work.
Key Takeaways
- Use threads for blocking I/O and processes for pure-Python CPU work in the standard build.
- Process pool functions, arguments, and results must cross a pickle boundary.
- Batch small process-map calls with
chunksize; it has no effect for thread pools. - An initializer runs once per worker, not once per task.
- Choose worker counts from cores for CPU work and resource limits for I/O.
- Interpreter pools provide isolated interpreters with separate GILs in Python 3.14+.
5Write asynchronous programs with asyncio
An event loop can coordinate many waiting operations in one thread when each operation gives control back while it waits. Build coroutines, schedule tasks together, and choose how their lifetimes and failures relate. Deadlines request cancellation and allow cleanup. Blocking calls and shared updates across awaits need special attention to keep the loop responsive and the results correct.
5.1 Run a coroutine on the event loop
asyncio lets many tasks share one thread. Its event loop runs a ready task until that task gives up control. This is cooperative multitasking: tasks cooperate by suspending at awaits, including awaits performed by async with and async for.
Define, call, and await
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
result = await fetch("a", 1)
print(result)
asyncio.run(main())
async def defines a coroutine function. Calling fetch("a", 1) creates a coroutine object; it does not execute the function body by itself. await runs or waits for an awaitable and obtains its value. Coroutines, tasks, and asyncio futures are awaitables.
Here asyncio.sleep(1) stands in for a network wait. While that wait is unfinished, the loop can run another ready task. After about one second, fetch returns and the program prints a done.
An await does not necessarily suspend. If its result is already available, execution can continue immediately. The useful scheduling point occurs when an await actually waits. Code between suspension points runs without another task in the same loop interrupting it.
Start the loop once
asyncio.run(main()) creates an event loop, runs the entry coroutine, and closes the loop after it finishes. Use it at a script's entry point. Calling it inside an already running loop in the same thread raises RuntimeError. A notebook with an active loop commonly lets you write await main() directly.
Ordinary scripts require await inside async def. A top-level script await is a syntax error. The asyncio REPL, started with python -m asyncio, also supports top-level awaits interactively.
Consecutive awaits still run in sequence
async def main():
first = await fetch("a", 0.3)
second = await fetch("b", 0.1)
third = await fetch("c", 0.2)
print(first, second, third)
Each call starts only after the previous await returns. The waits add to about 0.6 s. Using async def does not automatically schedule every call concurrently; create tasks or use gather() to overlap independent calls.
Calling a coroutine and discarding it also fails to run the body. Python can warn that it was never awaited. Await it or schedule it as a task, and keep track of its outcome.
Keep the waiting path asynchronous
Thousands of mostly waiting tasks use less memory than thousands of threads. The event loop needs asynchronous waiting operations, such as those supplied by async HTTP clients. Calling a blocking library directly occupies the sole event-loop thread.
A coroutine resembles a generator in its ability to pause and retain local variables. A generator yields values to its caller; a coroutine uses awaits to cooperate with the event loop and await other work.
Key Takeaways
- Calling a coroutine function creates an object; awaiting or scheduling runs it.
- The event loop switches tasks at suspension points.
- Use
asyncio.run()once at a script entry point. - Consecutive awaits do not overlap calls that have not yet been scheduled.
5.2 Give concurrent tasks a clear lifetime
A task schedules a coroutine on the event loop. asyncio.create_task(coro) returns a task you can later await. Under normal scheduling it starts when the current task gives control back to the loop. Keep a reference until you retrieve its outcome.
Overlap waits with gather
Using the fetch(name, delay) coroutine that awaits asyncio.sleep(delay) and returns f"{name} done":
results = await asyncio.gather(
fetch("a", 0.3),
fetch("b", 0.1),
fetch("c", 0.2),
)
The result is ['a done', 'b done', 'c done'] after about 0.3 s. Completion order is b, c, a, but gather preserves argument order. It schedules the supplied coroutines together. In contrast, [await fetch(name, delay) for name, delay in jobs] finishes each call before starting the next.
By default, a gather failure reaches the caller while the other awaitables continue. return_exceptions=True makes failures entries in the result list, allowing every outcome to be inspected. Inspect those entries before treating them as successful data.
Group work that should succeed together
A TaskGroup, available since Python 3.11, owns its tasks and waits for them at context exit:
async def main():
async with asyncio.TaskGroup() as group:
first = group.create_task(fetch("a", 0.3))
second = group.create_task(fetch("b", 0.1))
print(first.result(), second.result())
On successful exit, both results are ready. The group provides the task references and the place where failures are retrieved.
If a child raises an ordinary error such as ValueError, the group requests cancellation of its siblings, waits for cleanup, and raises an ExceptionGroup. Handle the relevant grouped errors with except*:
try:
async with asyncio.TaskGroup() as group:
group.create_task(load_first())
group.create_task(load_second())
except* ValueError as errors:
print("invalid input:", errors)
load_first and load_second stand for async loaders. A child cancelled with CancelledError alone does not trigger sibling cancellation. Also distinguish a gather failure from program shutdown: siblings left running by gather can later be cancelled when asyncio.run() shuts the loop down.
Choose completion-order reading deliberately
With plain iteration, asyncio.as_completed(tasks) gives awaitables whose results you await:
for next_result in asyncio.as_completed(tasks):
value = await next_result
print(value)
Python 3.13+ also allows async iteration, which yields completed task or future objects. If the inputs were tasks, those same objects can identify the source.
The loop holds weak task references, so keep your created tasks in a list or set, or let a TaskGroup own them. In Python 3.15+, group.cancel() requests an early, non-error group exit, cancelling unfinished children and the active group body.
Key Takeaways
- Creating tasks schedules concurrent work; keep references and retrieve outcomes.
gather()returns argument order even when tasks finish out of order.- A TaskGroup waits for its children and cancels siblings after an ordinary child failure.
- A cancelled child alone does not trigger TaskGroup sibling cancellation.
- Default gather failure leaves sibling awaitables running.
- Plain
asyncio.as_completed()iteration yields objects to await; async iteration in 3.13+ yields completed tasks or futures.
5.3 Set async deadlines and allow cleanup
A task may wait too long, fail, or be cancelled because its result is no longer needed. Give the work a deadline and a clear cleanup path. Async cancellation is cooperative: it delivers an exception into the task, allowing cleanup to run.
Put the deadline around the intended scope
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return name
async def timed_fetch(name, delay):
try:
async with asyncio.timeout(1):
return await fetch(name, delay)
except TimeoutError:
return f"{name}: timeout"
async def main():
results = await asyncio.gather(
timed_fetch("a", 0.2),
timed_fetch("b", 3),
timed_fetch("c", 0.5),
)
print(results)
asyncio.run(main())
The output is ['a', 'b: timeout', 'c'] after about one second, plus cleanup and scheduling costs. Each request owns a separate deadline. asyncio.timeout() cancels overdue work and translates its cancellation into TimeoutError as the context exits. Catch that exception outside the async with block.
Wrapping the entire gather in a timeout would instead put one deadline on the batch and cancel work still unfinished when it expires. Choose per-call or batch scope from the behavior you need.
A timeout includes a cancellation request
await asyncio.wait_for(operation(), timeout=1) limits one awaitable. On timeout it cancels the operation and waits for cancellation to finish before raising TimeoutError. Cleanup can take longer than the stated timeout; one second is not a hard bound on total elapsed time.
This differs from an executor future's result timeout, which only stops waiting for a still-running worker. An async timeout asks the awaited work to stop, though the work must cooperate.
Let cancellation travel outward
task.cancel() requests cancellation, normally delivering asyncio.CancelledError at a suspension point. Use try/finally or async with for cleanup. If catching cancellation to log or clean up, re-raise it:
try:
await operation()
except asyncio.CancelledError:
print("operation cancelled")
raise
finally:
release_resources()
operation and release_resources stand for the work and its cleanup. CancelledError inherits from BaseException, so except Exception does not catch it. Swallowing it can break timeout and TaskGroup behavior.
Retrieve every background outcome
An error is stored in its task. Awaiting the task, or calling result() or exception() after completion, retrieves it. Otherwise asyncio can log that the exception was never retrieved when the task is collected. A TaskGroup gives related work a shared lifetime and propagates its errors.
shield(inner_task) prevents cancellation of the caller from passing through that await to the inner task. The caller still receives cancellation. Keep a reference to the inner task and arrange to await it before shutdown; shielding alone does not guarantee completion, and direct cancellation of the inner task still works.
Key Takeaways
- Choose whether a timeout belongs to one call or the whole batch.
- Catch
TimeoutErroroutside the timeout context. wait_for()waits for cancellation cleanup, which can exceed its timeout.- Use
finallyfor cleanup and re-raise caughtCancelledError. - Retrieve task exceptions; keep shielded work referenced and awaited before shutdown.
5.4 Keep blocking work off the event loop
Async syntax does not turn a blocking call into a cooperative wait. time.sleep(), blocking HTTP calls, and long CPU loops occupy the event-loop thread until they return. Every other task waits too.
Move blocking I/O to a thread
Three coroutines each calling time.sleep(0.3) take about 0.9 s together. Changing that call to await asyncio.sleep(0.3) lets the waits overlap in about 0.3 s.
When a blocking function has no async equivalent, use to_thread():
import asyncio
import time
def read_legacy(name):
time.sleep(0.3)
return name.upper()
async def main():
values = await asyncio.gather(
*(asyncio.to_thread(read_legacy, name)
for name in ["oak", "elm", "ash"])
)
print(values)
asyncio.run(main())
to_thread(func, *args) runs the blocking call in a worker thread and exposes an awaitable result. It preserves event-loop responsiveness. In standard CPython, using it for a pure-Python CPU loop still leaves that loop competing for the GIL.
Send CPU work to a process pool
For expensive pure-Python parsing, obtain the running loop and await a process-pool call:
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(pool, parse, data)
Here pool is a ProcessPoolExecutor created under a script's main-module guard, and parse is an importable top-level function. Arguments and results must be picklable. Keep the pool available across calls so startup is not repeated for every document.
An occasional await asyncio.sleep(0) can let other tasks run during a long loop. It improves responsiveness without reducing the computation. Debug mode, asyncio.run(main(), debug=True), reports slow callbacks or task steps; the default threshold is 0.1 s.
Bound active requests
sem = asyncio.Semaphore(2)
async def limited(i):
async with sem:
await asyncio.sleep(0.2)
return i
Six tasks run together through gather() need about three rounds of two, or 0.6 s. Only the guarded operation consumes a permit. This limits simultaneous access; it is not a limit on requests per second.
Watch for shared state across awaits
Tasks can race in one thread. Suppose each task reads count, awaits asyncio.sleep(0), then writes the old value plus one. If 100 tasks all read zero before any writes, they finish with one. The await split the logical update.
Keep the read and write together without a suspension point, or protect the operation with one shared asyncio.Lock and async with lock:. Use asyncio's synchronization tools for tasks in one loop. They are not thread-safe. A contended threading.Lock blocks the loop's thread and can prevent its owner task from resuming to release it.
Key Takeaways
- Blocking calls occupy the sole event-loop thread.
- Use
to_thread()for blocking I/O and a process executor for heavy Python computation. - Yielding with
sleep(0)improves responsiveness without speeding computation. - An async semaphore bounds simultaneous operations, not requests per second.
- A shared update can race when an await separates its read from its write.
- Use asyncio locks inside the event loop; they do not coordinate threads.
6Choose, combine and measure concurrency models
The useful concurrency model follows the measured bottleneck: waiting through blocking or async libraries, computation under the GIL, or a mixture of stages. Each choice adds costs that the whole program must earn back. Compare complete jobs on the same inputs, verify their outputs, and use speedup, efficiency, and the sequential fraction to explain where extra workers help and where scaling stops.
6.1 Choose a model from the slow stage
Start with a measured bottleneck. A pool or event loop is useful when its extra coordination costs less than the time it saves. A faster algorithm or one batch request may solve the problem before concurrency is needed.
Follow the work
- Time the sequential program and locate the slow stage.
- Decide whether that stage mainly waits or computes.
- For waiting, inspect whether its library blocks the calling thread or offers async operations.
- For computation, check the interpreter build and whether the expensive library releases the GIL.
| Workload | Useful starting choice | Main cost or constraint |
|---|---|---|
| Blocking I/O with tens or hundreds of waits | Thread pool | Shared-state safety and service limits |
| Thousands of waits through async libraries | asyncio | Every waiting path must cooperate |
| Independent pure-Python CPU work, standard build | Process pool | Startup, pickling, and separate memory |
| CPU work with GIL disabled or released by a library | Measure a thread pool | Compatibility and synchronization |
Counts describe scale, not hard cutoffs. A working async library and the program's structure matter as much as the number of jobs.
Apply the sequence
A script downloads 500 pages using blocking requests calls. The network waits dominate, and rewriting the client is unnecessary to overlap them. A thread pool is a direct fit. Twenty workers could be a trial setting, but choose the actual limit from the server's published rules and responses. A concurrency limit does not by itself enforce a rate limit; slow or reschedule requests when needed.
A statistics program uses pure-Python loops on 40 independent in-memory datasets, taking several seconds each. On standard CPython, choose a process pool so separate GILs allow several cores to compute. Use about one process per usable core and include the cost of copying datasets when measuring.
A chat service maintains 10,000 mostly idle connections using async network operations. Asyncio can keep those tasks waiting with less memory than a thread per connection. A blocking call in any handler would still hold up the loop.
Combine stages with different needs
A crawler downloads pages asynchronously but parses them with slow Python loops. Keep network operations on the event loop and await parsing in a process executor. The parsing function must remain importable and its inputs picklable. The event loop can handle other connections while parsing runs on other cores.
Threads share memory conveniently but need coordination around changes. Processes separate memory but require explicit messages. Asyncio makes suspension points visible but relies on cooperative code. Choose those costs deliberately. Creating a separate process for every tiny I/O operation pays interpreter and transfer costs without gaining useful CPU parallelism. Likewise, asyncio alone cannot divide a CPU loop across cores.
Key Takeaways
- Measure the slow stage before choosing a concurrency model.
- Match blocking I/O to threads and large async waiting workloads to asyncio.
- Use processes for independent pure-Python CPU work with the GIL active.
- Mixed pipelines can combine async downloads with process-based computation.
- Choose limits from resources and service policies, then measure.
6.2 Measure the whole job and verify its output
A concurrent version is useful only if it gives the required results and improves the time that matters. Compare it with a sequential baseline on the same inputs, machine, and interpreter configuration.
Time what the user waits for
Use time.perf_counter() around the complete job, including pool startup, sending inputs, collecting results, and shutdown. process_time() in a pool's parent counts the parent's CPU consumption, leaving out child computation; it can make an expensive process job look almost free.
Repeat measurements and report a median or clearly identified best time. Keep workload size and output checks the same. Record the Python version, usable cores, worker count, and GIL state. In Python 3.13+, sys._is_gil_enabled() checks that state after the benchmark's libraries have been imported.
Calculate speedup and efficiency
Speedup compares the sequential duration with the concurrent duration:
An 8.0 s sequential job taking 2.5 s with four workers has speedup 3.2. Efficiency divides speedup by the worker count:
This summarizes the measured scaling; it does not identify the cause of lost time. Worker startup, serialization, scheduling, uneven chunks, and lock waits can all reduce performance.
Estimate the sequential limit
Amdahl's law models a fixed workload with parallel fraction on workers, assuming ideal distribution and no extra overhead:
For 90% parallel work and four workers, the sequential fraction is 0.1 and the divided parallel fraction is 0.225. Their sum is 0.325, giving an ideal speedup of about 3.08. With unlimited workers the parallel part tends toward zero, but the sequential tenth remains: speedup cannot exceed 10 in this model.
Real overhead lowers that ideal. Tiny tasks may spend more time traveling between workers than computing. Batch small process tasks with chunksize and measure again.
Stop adding workers when work runs out
Ten 0.5 s waits take about 5 s with one worker, 1 s with five, and 0.5 s with ten. Twenty workers still have only ten waits to overlap. CPU work similarly gains no extra core parallelism from workers beyond the usable cores.
Check correctness across many runs
Compare totals, returned values, and expected failures before celebrating speed. Completion order can differ: compare keyed outputs, or sorted results when sorting preserves the meaning. Avoid converting to a set if duplicate outputs matter.
Repeat correctness checks because races depend on timing. A passing test run cannot establish that an unprotected update is safe; inspect how shared accesses are coordinated. Benchmark the correct design, including its locks and cleanup, so the reported improvement belongs to the program you can actually use.
Key Takeaways
- Time the entire job with
perf_counter(), including startup and shutdown. - Compute speedup as sequential time divided by concurrent time.
- Efficiency divides speedup by workers; Amdahl's law exposes the sequential limit.
- Repeat measurements and record interpreter, GIL state, cores, and workload.
- Check outputs with ordering and duplicates handled correctly before comparing speed.
- Batch tiny work and stop adding workers when resources or independent work are exhausted.
Python Concurrency examples
1Find the bottleneck before choosing workers
10 steps
- 1IntroductionTwo slow jobs, two different causes
A program reads remote reports and then calculates statistics. Both stages feel slow, but they may need different changes. First identify whether each stage spends its time waiting (I/O-bound) or computing (CPU-bound). Then decide whether taking turns can save elapsed time or whether calculations need separate cores. The interpreter build helps determine which Python workers can use those cores: in standard CPython, the GIL lets only one thread run Python bytecode at a time.
- 2ExampleMeasure the waiting stage
The sequential reader takes 12 s of wall time and 0.3 s of CPU time.
perf_counter()measures the elapsed wait the user experiences;process_time()measures this process's computation. Most of the 12 s is spent waiting outside the CPU, so the stage is I/O-bound. Overlapping independent reads can use time that otherwise passes without useful work. - 3ExampleDraw the overlap
Suppose six independent reads each wait 0.4 s. One after another they need about 2.4 s. If all six waits start together, they end after about 0.4 s, plus overhead. One core is enough for this overlap: it can start another read while the first is waiting. Several jobs are in progress, but their Python instructions need not execute simultaneously.
- 4ChallengePredict a CPU timeline
Three independent pure computations each require 1 s on one core. What happens if a single core takes turns among them? What could three free cores change?
---reveal---
One core still needs about 3 s of computation, plus switching costs. Three free cores can compute simultaneously and approach 1 s plus overhead. Taking turns gives concurrency; simultaneous computation adds parallelism.
- 5ExplanationLocate the GIL restriction
In a standard CPython interpreter, the GIL lets one thread execute Python bytecode at a time. Three threads running those Python calculations still take turns, even if the machine has idle cores. Separate processes have separate interpreters and GILs, so they can use the free cores. The restriction belongs to this interpreter implementation, not to the definition of concurrency.
- 6ConnectionExplain why I/O threads work
During a blocking socket read or
time.sleep(), a thread releases the GIL. Another thread can execute while that wait continues. That makes a thread pool useful for the report reader. Some compiled libraries also release the GIL during heavy operations, so the phrase "CPU-bound" alone is not enough to reject threads when the computation happens inside such a library. - 7TipCheck capability and current state
A free-threaded CPython build can execute Python threads on several cores with the GIL disabled. It was experimental in 3.13 and supported from 3.14. Check build capability with
sysconfig.get_config_var("Py_GIL_DISABLED"). In Python 3.13+,sys._is_gil_enabled()tells whether the GIL is active now. An incompatible extension can turn it on again. - 8ChallengeRepair the thread-safety claim
A developer says, "Our standard build has a GIL, so two threads can safely check a shared cache and then insert a missing value without coordination." What is wrong with that reasoning?
---reveal---
The GIL protects interpreter internals, not the whole check-and-insert decision. Another thread can change the cache between those actions. Protect the logical operation with one shared lock, or avoid shared writes.
- 9ChallengeChoose for both stages
The reader uses a blocking library. The statistics stage is independent pure-Python work, and the GIL is active. What starting choices fit the two stages, and why would asyncio alone not solve both?
---reveal---
Use a thread pool to overlap reads and processes to run calculations on several cores. Asyncio can coordinate async waits, but its single event-loop thread does not parallelize the CPU stage.
- 10RecapUse evidence to choose the next step
Identify the time that can be saved: waiting can overlap, while computation needs less work or simultaneous execution on free cores. In standard CPython, threads help blocking I/O and processes help independent Python calculations. A free-threaded build or a library that releases the GIL can change CPU-thread scaling. Shared program rules still need synchronization.
2Run a small thread worker team
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive every job a path to completion
- 2ExamplePrepare the target without calling it
- 3ExampleStart the whole group
- 4ChallengeFind the missing failure
- 5TipRead a timed join correctly
- 6ExampleTrace two reservations
- 7ExampleShare a lock around the decision
- 8ChallengeChoose the useful lock boundary
- 9ExplanationPut jobs on a queue
- 10ExampleAccount for stop messages too
- 11ChallengeFinish all the consumers
- 12ConnectionSeparate signals from permits
- 13ChallengeRepair the complete worker design
- 14RecapFollow work, state, and shutdown separately
3Split a calculation across processes
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMove a calculation to separate interpreters
- 2ExampleDefine an importable worker
- 3ExampleGuard startup during import
- 4ChallengePredict an upgrade problem
- 5ExampleCalculate each partial answer
- 6Key InsightChoose what should cross the boundary
- 7ChallengeRepair the invisible result
- 8TipProtect truly shared storage
- 9ConnectionRead before joining a queue producer
- 10ChallengeChoose a complete repair
- 11RecapMake the boundaries explicit
4Collect outcomes from a reusable pool
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate work from its outcome
- 2ExampleSubmit without waiting immediately
- 3ChallengeLocate the accidental sequence
- 4ExplanationSeparate ordered output from finishing order
- 5ExampleKeep each future tied to its input
- 6ExampleReport one failure and continue
- 7ChallengePredict the visible results
- 8Key InsightRead a timeout as a limit on waiting
- 9TipUse wait when a set is enough
- 10ConnectionChange the worker model
- 11ExplanationReduce messages and repeated setup
- 12ChallengeChoose a resource-based configuration
- 13ChallengeRepair the whole result loop
- 14RecapUse futures to make outcomes visible
5Keep async tasks responsive and accountable
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionOne thread can manage many waits
- 2ExplanationCreate a coroutine object
- 3ExampleRun the entry coroutine
- 4ChallengePredict two consecutive awaits
- 5ExampleSchedule both before they finish
- 6ExplanationLet a group own related work
- 7ChallengeChoose the needed failure behavior
- 8TipKeep outcomes reachable
- 9ExampleSet one deadline per request
- 10ConnectionMove the deadline to change its scope
- 11ExampleAllow cancellation to finish
- 12ChallengeInterpret a late timeout result
- 13ExampleFind the blocking line
- 14ConnectionMove work to a suitable worker
- 15ExampleLimit simultaneous operations
- 16ChallengeTrace the race across an await
- 17TipUse synchronization for the loop
- 18ChallengeRepair a mixed async pipeline
- 19RecapSchedule, await, and clean up
6Choose a design and test its gain
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the design earn its complexity
- 2ExampleMatch a blocking service client
- 3ChallengeHandle a different expensive stage
- 4ExplanationTime the complete run
- 5ExampleCalculate the measured gain
- 6ExampleEstimate a serial ceiling
- 7ChallengeDistinguish two ways to improve scaling
- 8ConnectionCheck output meaning before comparing times
- 9Key InsightRecognize exhausted work
- 10ChallengeChoose the next experiment
- 11RecapKeep correctness inside the benchmark
Python Concurrency practice questions
Set 1: Recognize workloads and schedule independent work10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
load(path) needs one string argument, and path is "report.csv". How should a thread be constructed so the call runs when the thread starts?Show answerHide answer
(path,) a tuple. Calling load(path) while constructing the thread executes it immediately; passing the string itself as args instead unpacks its characters into separate arguments.Question 4 of 10
stock > 0 and then subtracts one. What lock boundary prevents both from reserving the last item?Show answerHide answer
Question 5 of 10
Show answerHide answer
if __name__ == "__main__":. Moving the worker inside that block would make it unavailable as an ordinary importable target.Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
await gather(a(), b(), c()) produce if the names are "a", "b", and "c"?Show answerHide answer
Question 9 of 10
ValueError while the other is suspended in a long async wait. The waiting task allows cancellation and cleans up in finally. What happens when the group exits?Show answerHide answer
ExceptionGroup containing the failure. Letting the sibling continue outside the group describes default gather behavior, not the shared lifetime enforced by TaskGroup.Question 10 of 10
Show answerHide answer
Set 2: Coordinate workers and keep the event loop moving10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
thread.join(timeout=0.1). What value does the join return, and what check reveals the worker state?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
None. What stop-message plan lets every consumer leave its blocking get()?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
join() before reading the queue, and the program hangs. What ordering addresses this problem?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
async with asyncio.timeout(0.4). Where should a handler catch the timeout created by that context?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace state, ordering, and process boundaries10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Py_GIL_DISABLED as 1, but after importing a C extension sys._is_gil_enabled() reports True. What explains these two results?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
n = 7 and each executes old = n; pause(); n = old + 2. What final values can result if both calls finish, and what lock boundary makes both additions reliable?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
multiprocessing.Value 200 times each. The code reads .value, calculates, and writes it back without holding its lock across the sequence. Some runs end below 800. What change addresses the cause?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
lambda x: 18 / x over [3, 6, 0, 2]. What does a single pass through the returned iterator yield before it raises?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
result(timeout=0.05) times out inside an executor context. The caller catches the timeout, calls cancel(), then exits the context. What should it expect?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
load(), another coroutine function. What expression obtains that value?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
gather(task_a, task_b, return_exceptions=True). Task A raises ValueError, and task B returns 27. What can the caller inspect after awaiting gather?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Diagnose interacting concurrency failures10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
CancelledError, closes its connection, then retries its long async wait indefinitely. Another child has raised ValueError. The group does not finish. What change addresses both cleanup and group completion?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Semaphore(3). All are scheduled together. About how long does the guarded work take, ignoring overhead?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Choose complete designs under changed conditions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
sys._is_gil_enabled() changes from False before library imports to True afterward; in the other it remains False. What explains different thread scaling, and what should a fair comparison check?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
None, otherwise process it and call task_done(). After all normal jobs, the producer queues one None and calls queue.join(). No processing fails. One consumer exits, two remain alive, and the join stays pending. What changes address both causes?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[0, 400) and [400, 900). What property lets the parent add those counts to count the entire range [0, 900) correctly?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
BrokenProcessPool, and new submissions fail. What is the appropriate pool-level recovery?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
main() in that environment?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
shield(inner_task) while keeping a reference to the inner task. The caller is cancelled, and the inner task has not been directly cancelled. What must the caller's surrounding program account for?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
threading.Lock, then awaits I/O. A second task in the same loop tries to acquire that lock and blocks. Why can neither task progress, and what lock fits this shared async operation?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Amdahl's law
Async deadline
Asyncio lock
Asyncio semaphore
Asyncio task
create_task() so it can later retrieve the outcome.Awaitable
await, including coroutine objects, tasks, and asyncio futures representing pending operations.B
Backpressure
put() wait when its backlog is full.Blocking call
time.sleep() inside async def prevents the loop from resuming other tasks during that wait.Bottleneck
Broken process pool
C
Cancellation cleanup
wait_for() running after its deadline while the operation releases resources.Cancellation request
CancelledError, normally when the coroutine is suspended at an await.Check-then-act race
Chunk size
Completion order
as_completed() loop to process ready outcomes before slower calls.Concurrency
Concurrency limit
Cooperative multitasking
Coordination overhead
Coroutine function
async def and produces a coroutine object when called, leaving its body to be awaited or scheduled.Coroutine object
CPU-bound workload
CPython
Critical section
D
Daemon thread
Done callback
E
Efficiency
Event
Event loop
Exception group
except*.Executor
submit() and future-based result collection.Exit code
F
FIFO queue
put() and get().Forkserver
Free-threaded build
Future
result() call waits for one report.G
Gather
Global interpreter lock
I
I/O-bound workload
Initializer
Input order
map() preserves when yielding results even if calls finish differently.Interpreter pool
L
Lost update
M
Main-module guard
if __name__ == "__main__": check that keeps script startup from running when the module is imported.Manager proxy
Mixed workload
Mutual-exclusion lock
P
Parallelism
Partial result
Pending-call cancellation
Pickling
Pipe
Process
Process queue
put() and get() operations across their separate memory.Producer-consumer pattern
R
Race condition
Rate limit
Reentrant lock
Result timeout
S
Semaphore
Sentinel
Sequential baseline
Shared value
get_lock() while incrementing a shared value so its read and write stay together.Shielding
Slow callback threshold
Spawn
Speedup
Submission
executor.submit(load, name) passes the function and argument without calling load in the caller.Switch interval
T
Target function
Task group
Thread
Thread join
None.is_alive() to see whether the worker is still running.Thread offloading
asyncio.to_thread() keeps connections responsive during a legacy blocking read.Thread safety
U
Unretrieved task exception
W
Wall-clock time
Worker pool
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.