Python Concurrency: Threads, Processes and asyncio

Learn when concurrency makes a Python program faster and which tool fits the job. Tell concurrency from parallelism and I/O-bound from CPU-bound work, and see how the global interpreter lock and the newer free-threaded builds affect threads. Write programs with 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

  1. 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 workloads
      Use 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 builds
      Describe 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.
  2. Start and coordinate threads with the threading module, 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 results
      Create threads with threading.Thread, run them at the same time, wait with join(), and collect results and errors correctly.
    • Find and fix race conditions with locks
      Recognize the interleavings that cause race conditions in shared data, and protect critical sections with threading.Lock without losing the benefit of concurrency.
    • Pass work between threads with queues and events
      Organize threads as producers and consumers around a thread-safe queue.Queue, stop them cleanly with sentinels or an Event, and limit simultaneous access with a semaphore.
  3. Run CPU-bound work in parallel with the multiprocessing module, write programs that start processes safely on every platform, and move data between processes without shared-state bugs.
    • Start processes safely with multiprocessing
      Create 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 processes
      Move 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.
  4. 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 futures
      Use ThreadPoolExecutor and ProcessPoolExecutor with submit() and map(), and read results, errors and status from Future objects.
    • Process results as they finish and handle errors and timeouts
      Read results in completion order with as_completed(), wait selectively with wait(), and handle failures, timeouts, cancellation and broken pools.
    • Configure thread, process and interpreter pools
      Choose the executor class for the work, set worker counts and batch sizes, prepare each worker once, and know what the newer interpreter pool offers.
  5. Define and run coroutines with async and await, 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 await
      Explain how the event loop runs coroutines cooperatively, write async def functions, await results and start a program with asyncio.run().
    • Run tasks concurrently with gather and TaskGroup
      Schedule coroutines as tasks, run them together with asyncio.gather() and asyncio.TaskGroup, and predict their results, timing and behavior when one fails.
    • Handle timeouts, cancellation and errors in async code
      Put time limits on awaits with asyncio.timeout() and asyncio.wait_for(), cancel tasks and clean up correctly, and avoid losing errors in background tasks.
    • Keep the event loop responsive and protect shared state
      Recognize 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.
  6. 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 workload
      Follow 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 correctness
      Time 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.

Python Concurrency study guide

6 chapters

1

Explain 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:

10×0.5=5 s

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
ModelWhere work runsMain use in standard CPython
ThreadsSeveral execution paths sharing one processOverlapping blocking I/O
ProcessesSeparate interpreters with separate memoryParallel pure-Python computation
asyncioTasks taking turns in one threadMany 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 settingPure-Python CPU threads
Standard build with GILTake turns executing bytecode
Free-threaded build with GIL disabledCan 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.
2

Run 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:

  1. Thread A reads 41.
  2. Thread B reads 41 and stores 42.
  3. 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 RLock for 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; thread join() 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.
3

Use 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
MethodHow the child startsUsual platform default
spawnNew interpreter importing the main moduleWindows and macOS
forkCopy of the parent processNo platform since Python 3.14
forkserverFork requested from a separate serverLinux 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 Value still needs its lock for read-modify-write updates.
  • Manager proxies trade flexibility for message overhead.
4

Run 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+.
5

Write 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 TimeoutError outside the timeout context.
  • wait_for() waits for cancellation cleanup, which can exceed its timeout.
  • Use finally for cleanup and re-raise caught CancelledError.
  • 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.
6

Choose, 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
  1. Time the sequential program and locate the slow stage.
  2. Decide whether that stage mainly waits or computes.
  3. For waiting, inspect whether its library blocks the calling thread or offers async operations.
  4. For computation, check the interpreter build and whether the expensive library releases the GIL.
WorkloadUseful starting choiceMain cost or constraint
Blocking I/O with tens or hundreds of waitsThread poolShared-state safety and service limits
Thousands of waits through async librariesasyncioEvery waiting path must cooperate
Independent pure-Python CPU work, standard buildProcess poolStartup, pickling, and separate memory
CPU work with GIL disabled or released by a libraryMeasure a thread poolCompatibility 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:

S=TsequentialTconcurrent

An 8.0 s sequential job taking 2.5 s with four workers has speedup 3.2. Efficiency divides speedup by the worker count:

E=3.24=0.8=80%

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 p on n workers, assuming ideal distribution and no extra overhead:

Smax⁡=1(1−p)+p/n

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

6 Walkthroughs

1

Find the bottleneck before choosing workers

10 steps
Classify two jobs, trace their timelines, and connect the results to CPython builds.
  1. 1
    IntroductionTwo 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.

  2. 2
    ExampleMeasure 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.

  3. 3
    ExampleDraw 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.

  4. 4
    ChallengePredict 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.

  5. 5
    ExplanationLocate 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.

  6. 6
    ConnectionExplain 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.

  7. 7
    TipCheck 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.

  8. 8
    ChallengeRepair 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.

  9. 9
    ChallengeChoose 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.

  10. 10
    RecapUse 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.

2

Run a small thread worker team

14 steps
Start overlapping tasks, repair a shared update, and give queue workers a clean stop.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive every job a path to completion
  2. 2
    ExamplePrepare the target without calling it
  3. 3
    ExampleStart the whole group
  4. 4
    ChallengeFind the missing failure
  5. 5
    TipRead a timed join correctly
  6. 6
    ExampleTrace two reservations
  7. 7
    ExampleShare a lock around the decision
  8. 8
    ChallengeChoose the useful lock boundary
  9. 9
    ExplanationPut jobs on a queue
  10. 10
    ExampleAccount for stop messages too
  11. 11
    ChallengeFinish all the consumers
  12. 12
    ConnectionSeparate signals from permits
  13. 13
    ChallengeRepair the complete worker design
  14. 14
    RecapFollow work, state, and shutdown separately
3

Split a calculation across processes

11 steps
Build a spawn-safe script and combine independent partial results in the parent.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMove a calculation to separate interpreters
  2. 2
    ExampleDefine an importable worker
  3. 3
    ExampleGuard startup during import
  4. 4
    ChallengePredict an upgrade problem
  5. 5
    ExampleCalculate each partial answer
  6. 6
    Key InsightChoose what should cross the boundary
  7. 7
    ChallengeRepair the invisible result
  8. 8
    TipProtect truly shared storage
  9. 9
    ConnectionRead before joining a queue producer
  10. 10
    ChallengeChoose a complete repair
  11. 11
    RecapMake the boundaries explicit
4

Collect outcomes from a reusable pool

14 steps
Submit independent calls, report completed results, and interpret deadlines and pool settings.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate work from its outcome
  2. 2
    ExampleSubmit without waiting immediately
  3. 3
    ChallengeLocate the accidental sequence
  4. 4
    ExplanationSeparate ordered output from finishing order
  5. 5
    ExampleKeep each future tied to its input
  6. 6
    ExampleReport one failure and continue
  7. 7
    ChallengePredict the visible results
  8. 8
    Key InsightRead a timeout as a limit on waiting
  9. 9
    TipUse wait when a set is enough
  10. 10
    ConnectionChange the worker model
  11. 11
    ExplanationReduce messages and repeated setup
  12. 12
    ChallengeChoose a resource-based configuration
  13. 13
    ChallengeRepair the whole result loop
  14. 14
    RecapUse futures to make outcomes visible
5

Keep async tasks responsive and accountable

19 steps
Run overlapping waits, group failures, set deadlines, and repair blocking calls and async races.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionOne thread can manage many waits
  2. 2
    ExplanationCreate a coroutine object
  3. 3
    ExampleRun the entry coroutine
  4. 4
    ChallengePredict two consecutive awaits
  5. 5
    ExampleSchedule both before they finish
  6. 6
    ExplanationLet a group own related work
  7. 7
    ChallengeChoose the needed failure behavior
  8. 8
    TipKeep outcomes reachable
  9. 9
    ExampleSet one deadline per request
  10. 10
    ConnectionMove the deadline to change its scope
  11. 11
    ExampleAllow cancellation to finish
  12. 12
    ChallengeInterpret a late timeout result
  13. 13
    ExampleFind the blocking line
  14. 14
    ConnectionMove work to a suitable worker
  15. 15
    ExampleLimit simultaneous operations
  16. 16
    ChallengeTrace the race across an await
  17. 17
    TipUse synchronization for the loop
  18. 18
    ChallengeRepair a mixed async pipeline
  19. 19
    RecapSchedule, await, and clean up
6

Choose a design and test its gain

11 steps
Match a two-stage job to workers, calculate its scaling, and verify equivalent output.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the design earn its complexity
  2. 2
    ExampleMatch a blocking service client
  3. 3
    ChallengeHandle a different expensive stage
  4. 4
    ExplanationTime the complete run
  5. 5
    ExampleCalculate the measured gain
  6. 6
    ExampleEstimate a serial ceiling
  7. 7
    ChallengeDistinguish two ways to improve scaling
  8. 8
    ConnectionCheck output meaning before comparing times
  9. 9
    Key InsightRecognize exhausted work
  10. 10
    ChallengeChoose the next experiment
  11. 11
    RecapKeep correctness inside the benchmark

Python Concurrency practice questions

50 Practice Questions in 5 sets

Set 1: Recognize workloads and schedule independent work10 Practice Questions

Question 1 of 10

A sequential network check takes 9 s of wall time and 0.15 s of CPU time. What kind of bottleneck do these measurements suggest?
  1. Most time is spent computing in Python.
  2. Most time is spent on parallel work.
  3. Most time is spent waiting for I/O.
  4. Most time is spent merging CPU results.
Show answerHide answer
Answer: C
The process uses little CPU time during the much longer elapsed run, so waiting dominates this sequential job. Overlapping independent waits may help. Calling it CPU-bound confuses the duration experienced by the user with the time the processor actually spends computing.

Question 2 of 10

Four threads run independent, long pure-Python loops in a standard CPython interpreter with its GIL active. Why do idle cores not make those loops run four times as fast?
  1. One thread at a time executes bytecode in that interpreter.
  2. Each loop has to wait for the main thread to collect its result.
  3. Each thread owns an interpreter that schedules the other threads.
  4. One process can execute on only one core regardless of its libraries.
Show answerHide answer
Answer: A
The active GIL restricts Python bytecode execution to one thread at a time within the interpreter. The loops take turns and add switching costs. The restriction is not a general one-core limit on every operation in a process: compiled code that releases the GIL can behave differently.

Question 3 of 10

A function 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?
  1. Thread(target=load(path), args=())
  2. Thread(target=load, args=path)
  3. Thread(target=load, args=(path))
  4. Thread(target=load, args=(path,))
Show answerHide answer
Answer: D
Pass the function object as the target and a one-item tuple as its arguments. The comma makes (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

Two threads reserve items from shared stock. Each checks stock > 0 and then subtracts one. What lock boundary prevents both from reserving the last item?
  1. One shared lock around the subtraction alone.
  2. One shared lock around the check and subtraction.
  3. One new lock inside each call around both lines.
  4. One shared lock around the check alone.
Show answerHide answer
Answer: B
The decision and update must use one protected view of stock, so they belong inside the same shared critical section. Locking only the subtraction still lets both checks see the last item as available. Separate locks created for each call also fail to coordinate the two threads.

Question 5 of 10

A script defines its worker at module level but creates and starts a spawned process at module level too. A bootstrapping error occurs. What change addresses its cause?
  1. Move the worker definition inside the startup code.
  2. Put process creation and startup under the main-module guard.
  3. Choose a larger timeout for the child process join.
  4. Replace each plain input with a global variable.
Show answerHide answer
Answer: B
Spawn imports the main module in the child, so unguarded startup tries to launch another process during that import. Guard process creation and startup with if __name__ == "__main__":. Moving the worker inside that block would make it unavailable as an ordinary importable target.

Question 6 of 10

Eight independent calls each wait 0.3 s. A thread pool has four workers, and all calls are submitted before results are read. About how long does the waiting work take, ignoring overhead?
  1. 0.3 s
  2. 1.2 s
  3. 2.4 s
  4. 0.6 s
Show answerHide answer
Answer: D
Four calls can wait in the first round, then the remaining four in the second, giving about 0.6 s. A single 0.3 s round would need eight workers available for these calls. Reading futures after submission does not serialize work that the executor has already scheduled.

Question 7 of 10

An async function contains a print statement. The program calls the function and discards the returned object, without awaiting or scheduling it. What happens to that print statement?
  1. It does not run merely because the coroutine was called.
  2. It runs immediately before the coroutine object is returned.
  3. It runs automatically at the next ordinary function call.
  4. It runs when the unused coroutine is garbage-collected.
Show answerHide answer
Answer: A
Calling an async function creates a coroutine object without executing its body. Awaiting it or scheduling it as a task makes the body run. Garbage collection may produce a never-awaited warning; it does not execute the discarded coroutine to complete its print statement.

Question 8 of 10

Three async calls return their names after waits of 0.5 s, 0.2 s, and 0.4 s. What result does await gather(a(), b(), c()) produce if the names are "a", "b", and "c"?
  1. ["b", "c", "a"] after about 0.5 s.
  2. ["a", "b", "c"] after about 1.1 s.
  3. ["a", "b", "c"] after about 0.5 s.
  4. ["b", "c", "a"] after about 1.1 s.
Show answerHide answer
Answer: C
Gather schedules the waits together but returns values in argument order, so the longest wait sets the approximate batch duration. Completion order would be b, c, a, which is not the order of gather's result list. Adding all three waits would describe consecutive unscheduled awaits.

Question 9 of 10

Two tasks are created inside a TaskGroup. One raises 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?
  1. The sibling is cancelled and cleaned up; an error group reaches the caller.
  2. The sibling completes its original wait; a plain ValueError reaches the caller.
  3. The sibling keeps running outside the group; a plain ValueError reaches the caller.
  4. The sibling is cancelled without cleanup; the group returns its successful results.
Show answerHide answer
Answer: A
The ordinary child failure makes TaskGroup cancel unfinished siblings and wait for their cancellation cleanup. It then raises an 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

A utility uses a blocking client for 180 independent database reads. Most elapsed time is waiting, and the database allows a small number of simultaneous reads. What starting design fits?
  1. A process per read with a copied database connection.
  2. An async wrapper that calls each blocking read directly.
  3. A bounded thread pool around the existing reads.
  4. A CPU-sized process pool to eliminate serialization.
Show answerHide answer
Answer: C
A bounded thread pool can overlap blocking waits while respecting the database's simultaneous-use limit. An async wrapper that directly calls the blocking client still occupies the event-loop thread. Processes add startup and transfer costs, and copying a live connection is not a sound input strategy.
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

One core alternates between several tasks while their network replies are pending. What term describes the overlapping progress, without simultaneous computation?
  1. CPU parallelism without concurrency.
  2. Concurrency without CPU parallelism.
  3. Concurrency with simultaneous bytecode execution.
  4. Sequential execution without overlapping work.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A worker is still running after thread.join(timeout=0.1). What value does the join return, and what check reveals the worker state?
  1. It returns False; is_alive() returns True.
  2. It raises TimeoutError; is_alive() returns True.
  3. It returns None; is_alive() returns False.
  4. It returns None; is_alive() returns True.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A producer has queued all jobs for five consumers. Each consumer exits when it retrieves None. What stop-message plan lets every consumer leave its blocking get()?
  1. Queue five None sentinels after the jobs.
  2. Queue one None and join all five consumers.
  3. Set an unrelated Event and leave the queue empty.
  4. Call task_done() five extra times from the producer.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A child sends a very large result on a multiprocessing queue. The parent calls join() before reading the queue, and the program hangs. What ordering addresses this problem?
  1. Join twice, then receive the result.
  2. Replace the queue with a normal shared list.
  3. Receive the result, then join the producer.
  4. Wait for the child to exit before draining output.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A caller wants to process successful executor results as soon as their tasks finish. What iterator supplies the corresponding completed futures?
  1. executor.map(func, inputs)
  2. iter(futures) in submission order
  3. as_completed(futures)
  4. wait(futures).not_done
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A process pool maps a tiny function over 600,000 values, spending most of its time passing individual calls. What setting directly reduces the number of work messages?
  1. A larger chunksize for process map().
  2. A larger chunksize for a thread pool instead.
  3. An initializer that runs the tiny function once.
  4. A larger timeout for each result read.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A request is wrapped in async with asyncio.timeout(0.4). Where should a handler catch the timeout created by that context?
  1. Inside the block, as TimeoutError from the context.
  2. Outside the block, as the context's ValueError.
  3. Inside the block, by ignoring every BaseException.
  4. Outside the async with block, as TimeoutError.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An async service calls a legacy blocking file reader, then does a long pure-Python analysis of the returned data. The GIL is active. What design keeps the loop responsive and permits CPU parallelism?
  1. Await the read in a thread and run the analysis directly in the coroutine.
  2. Await the read in a thread and the analysis in a process pool.
  3. Run the read directly in the coroutine and await analysis in a process pool.
  4. Run both stages as coroutines that call the same blocking functions.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A service keeps 7,000 mostly idle connections using asynchronous network operations. What concurrency model offers a natural starting point?
  1. One process per open connection.
  2. Asyncio tasks in an event loop.
  3. A process pool for each wait.
  4. Sequential awaits, one at a time.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A job takes 15 s sequentially and 5 s with five workers. A separate fixed-workload model says 20% is sequential. How do the measured speedup and that model's ideal five-worker speedup compare?
  1. Measured 3; ideal 5, so the model confirms perfect scaling.
  2. Measured 0.33; ideal about 2.78, so concurrency slowed the job.
  3. Measured 3; ideal 2.78, so overhead explains exceeding the ideal.
  4. Measured 3; ideal about 2.78, so the model and measurement need reconciliation.
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

A Python 3.14 free-threaded build reports Py_GIL_DISABLED as 1, but after importing a C extension sys._is_gil_enabled() reports True. What explains these two results?
  1. The build lacks free-threading support despite its configuration value.
  2. The process has two GILs, one for Python and one for the extension.
  3. The GIL is disabled because build configuration overrides runtime state.
  4. The build supports free threading, but the GIL is currently enabled.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two threads share 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?
  1. Only 11; lock just the assignment.
  2. 9 or 11; use one shared lock from the read through the write.
  3. 7 or 9; create a new lock around each complete call.
  4. Only 9; lock just the calculation of the new value.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A fast producer fills a bounded queue while consumers lag behind. How does the queue apply backpressure?
  1. get() discards the oldest item when capacity is reached.
  2. task_done() starts more consumers when the queue fills.
  3. put() waits when the queue reaches its capacity.
  4. join() automatically increases the queue's capacity.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A spawned process is passed a lambda and an open text file. How should its inputs and target be reorganized for ordinary pickling?
  1. Use a top-level function and pass the file path.
  2. Use a nested function and pass the open file.
  3. Keep the lambda and pass the file's iterator.
  4. Keep both objects and increase the join timeout.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Four processes increment a shared 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?
  1. Protect only the assignment to .value with its lock.
  2. Change the shared integer into an ordinary global integer.
  3. Protect each complete increment with value.get_lock().
  4. Join each process immediately after starting it to retain parallel updates.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A thread pool maps lambda x: 18 / x over [3, 6, 0, 2]. What does a single pass through the returned iterator yield before it raises?
  1. 6.0, then 3.0, then ZeroDivisionError.
  2. 6.0, 3.0, an exception value, then 9.0.
  3. 9.0, 6.0, then ZeroDivisionError.
  4. No values; the first failed call cancels every result.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A future is already running when 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?
  1. Cancellation succeeds, and context exit skips the running call.
  2. Cancellation fails, but the timeout forces immediate context exit.
  3. Cancellation succeeds, but only the result value is discarded.
  4. Cancellation fails, and context exit waits for the running call.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An async function in a script needs the value returned by load(), another coroutine function. What expression obtains that value?
  1. load
  2. await load()
  3. load() without awaiting
  4. asyncio.run without a call
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A caller uses 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?
  1. A list containing the ValueError object followed by 27.
  2. A ValueError raised directly before task B finishes.
  3. A list containing 27 followed by the ValueError object.
  4. A cancelled task B and an empty result list.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A concurrent result list arrives in a different order than the sequential baseline, and duplicate results are meaningful. What comparison preserves multiplicity while ignoring order?
  1. Compare sets built from each result list.
  2. Compare only the first value returned by each version.
  3. Compare sorted result lists when the values support sorting.
  4. Compare only the count of unique returned values.
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

A process waits for a remote storage response for most of its elapsed runtime. What kind of work dominates that stage?
  1. I/O-bound waiting.
  2. CPU-bound computing.
  3. Parallel computing.
  4. Shared-state locking.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A worker downloads a file without accessing shared data, then adds its byte count to a shared total. What lock placement keeps the total safe while allowing downloads to overlap?
  1. Lock the download and release before updating the total.
  2. Lock only the assignment after reading the total outside.
  3. Lock the shared read-modify-write update after downloading.
  4. Create a separate worker-local lock around the whole function.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Thread A holds lock X then waits for Y. Thread B holds Y then waits for X. Both need to update the same two structures. What design change prevents this circular wait without removing mutual exclusion?
  1. Change both locks to RLock but keep their acquisition order.
  2. Put a short sleep before each second lock acquisition.
  3. Keep both orders and join the threads with a longer timeout.
  4. Have both threads acquire X and then Y consistently.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A spawned child completes normally after changing a module-level dictionary. What should the parent expect from its own ordinary dictionary after joining the child?
  1. It receives the child's dictionary changes at join.
  2. Its own dictionary retains its previous contents.
  3. It becomes a manager proxy when the child starts.
  4. It is updated once the child exit code is zero.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Twelve independent 0.2 s waits are submitted together. Ignoring overhead, how do four workers and six workers compare for the whole batch?
  1. About 0.2 s with four; about 0.2 s with six.
  2. About 0.6 s with four; about 0.4 s with six.
  3. About 0.8 s with four; about 1.2 s with six.
  4. About 2.4 s with four; about 2.4 s with six.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A CPU process job repeatedly loads the same lookup table and sends one tiny input per call. It already has one worker per usable core. What two settings address these costs most directly?
  1. Load once in the parent only and increase the CPU worker count.
  2. Load once in each worker initializer and shorten result timeouts.
  3. Increase map chunksize and rebuild the table inside every call.
  4. Load once in each worker initializer and increase map chunksize.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

One TaskGroup child is explicitly cancelled; another continues waiting and later succeeds. The group body finishes normally, with no other errors. What happens at context exit?
  1. The group cancels the surviving child and raises an ExceptionGroup for cancellation.
  2. The group exits immediately and leaves the surviving child outside its lifetime.
  3. The group waits for the surviving child; cancellation alone does not cancel it.
  4. The group restarts the cancelled child and waits for both successful results.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A TaskGroup child catches 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?
  1. Close in finally and propagate cancellation instead of retrying.
  2. Close the connection and keep retrying until a new ValueError occurs.
  3. Return to the same wait and place a result timeout around the completed peer.
  4. Replace the group with gather while leaving the retry loop unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Nine equal async operations each wait 0.2 s inside one shared Semaphore(3). All are scheduled together. About how long does the guarded work take, ignoring overhead?
  1. 0.6 s
  2. 0.2 s
  3. 1.8 s
  4. 2.7 s
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fixed CPU workload is 75% parallelizable and 25% sequential. With four ideal workers and no added overhead, what speedup is possible now and what ceiling remains with unlimited workers?
  1. About 2.29 now; a ceiling of 3.
  2. About 3.00 now; a ceiling of 4.
  3. About 2.29 now; a ceiling of 4.
  4. About 4.00 now; no finite ceiling.
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

Two CPU-thread benchmarks use the same free-threaded executable and pure-Python algorithm. Both report build capability as 1. In one, 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?
  1. Identical build capability fixes scaling; compare elapsed times without further interpreter checks.
  2. Runtime GIL state differs; verify state after imports and keep the measured workload equivalent.
  3. An executable suffix fixes runtime state; compare only the configured thread counts and inputs.
  4. The algorithm changed its parallel fraction; use the build flag instead of checking active state.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Three consumers repeatedly get a queue item, return immediately on 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?
  1. Keep one sentinel and acknowledge all retrieved items, including that sentinel.
  2. Send three sentinels and acknowledge only the normal items after processing.
  3. Send three sentinels and acknowledge every retrieved item, including sentinels.
  4. Set an unrelated Event and acknowledge all normal jobs without adding sentinels.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two process workers return counts over integer ranges [0, 400) and [400, 900). What property lets the parent add those counts to count the entire range [0, 900) correctly?
  1. Both chunks contain the value 400 as a shared boundary.
  2. Each process modifies the same normal parent counter.
  3. Completion order determines which range is counted first.
  4. The chunks cover every intended input exactly once.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

One process worker is killed abruptly while futures remain pending. They raise BrokenProcessPool, and new submissions fail. What is the appropriate pool-level recovery?
  1. Create a new pool before submitting further work.
  2. Reuse the broken pool after reading one failed future.
  3. Change pending future timeouts so the worker restarts.
  4. Cancel one future so the pool recreates its processes.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A notebook already runs an event loop in the current thread. How should it run an entry coroutine main() in that environment?
  1. asyncio.run(main())
  2. main() and discard its object
  3. asyncio.run(main)
  4. await main()
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A caller awaits 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?
  1. The outer await completes normally while shield delays cancellation until the inner task finishes.
  2. The outer await is cancelled while inner work continues and still needs awaiting before shutdown.
  3. Both tasks are cancelled immediately because shield only changes exception logging.
  4. The inner task is guaranteed to finish even if the event loop shuts down immediately.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An async task holds a 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?
  1. The blocked acquire holds the loop thread; use one shared asyncio.Lock.
  2. The GIL serializes the network; use a separate threading.Lock in each task.
  3. The first await releases every lock; use a Semaphore created on each call.
  4. The lock is reentrant across tasks; use RLock to give each task a permit.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A service has thousands of async connections and performs occasional independent 2 s pure-Python analyses. It runs standard CPython. What design handles both stages while keeping connections responsive?
  1. Asyncio for connections, with analyses run directly between network awaits.
  2. A thread for each connection, with analyses submitted to the same thread pool.
  3. Asyncio for connections, with analyses awaited through a reusable process pool.
  4. A new process per connection, with each analysis run in the event-loop thread.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program starts one non-daemon writer and one daemon monitor. The main thread returns while the writer is still running. What happens to the process lifetime?
  1. The main thread immediately ends both workers regardless of daemon status.
  2. The writer keeps the process alive; the daemon may be cut off once only daemons remain.
  3. The daemon keeps the process alive after the writer exits until it is joined.
  4. Both workers are guaranteed a clean exit because the main thread returned normally.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A Python 3.14 application considers InterpreterPoolExecutor for CPU work. What boundary still applies despite its workers living inside one process?
  1. Workers use isolated interpreters and serialize calls between them.
  2. Workers freely share mutable Python objects as ordinary threads do.
  3. Workers all execute Python bytecode under the same interpreter GIL.
  4. Workers require no compatibility checks for imported extension modules.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

78 Key Terms, each with its definition

A

Amdahl's law
Amdahl's law gives an ideal fixed-workload speedup from the parallel fraction and worker count, exposing the remaining sequential limit.
Amdahl's law limits ideal speedup to 5 when 20% of a fixed workload must remain sequential.
Async deadline
An async deadline requests cancellation when an awaited operation or block exceeds its allowed time, letting async cleanup still run.
A separate async deadline for each request lets fast calls succeed while a slow call times out.
Asyncio lock
An asyncio lock permits one task at a time into a critical section and suspends competing tasks without blocking the event-loop thread.
An asyncio lock can protect a shared update spanning an await while competing tasks wait cooperatively.
Asyncio semaphore
An asyncio semaphore limits how many tasks enter a guarded async operation at once, suspending other tasks until permits become available.
An asyncio semaphore with three permits lets nine equal requests run in three rounds of guarded work.
Asyncio task
An asyncio task schedules and tracks one coroutine, allowing its result, failure, or cancellation to be retrieved after execution.
The program saves each asyncio task returned by create_task() so it can later retrieve the outcome.
Awaitable
An awaitable is an object usable with await, including coroutine objects, tasks, and asyncio futures representing pending operations.
An unfinished network awaitable lets its waiting task suspend while the loop runs another ready task.

B

Backpressure
Backpressure slows an upstream producer when downstream work falls behind, such as making queue put() wait when its backlog is full.
A bounded job queue applies backpressure when a fast producer gets ahead of slower workers.
Blocking call
A blocking call occupies its calling thread until it returns, preventing an event loop in that thread from running another ready task.
A blocking call to time.sleep() inside async def prevents the loop from resuming other tasks during that wait.
Bottleneck
A bottleneck is the stage or limited resource that dominates a job's elapsed time, guiding where a performance change can matter.
Faster parsing barely helps when remote responses remain the bottleneck for almost the entire run.
Broken process pool
A broken process pool is an unusable process executor after an abrupt worker failure, potentially failing pending futures as well.
After a worker is killed abruptly, a broken process pool must be replaced before new submissions.

C

Cancellation cleanup
Cancellation cleanup releases resources while a task responds to a stop request, potentially extending the elapsed time beyond its timeout.
Cancellation cleanup can keep wait_for() running after its deadline while the operation releases resources.
Cancellation request
A cancellation request asks an async task to stop by delivering CancelledError, normally when the coroutine is suspended at an await.
A worker handles a cancellation request by releasing its connection and letting CancelledError propagate.
Check-then-act race
A check-then-act race occurs when shared state changes after a condition is checked but before the related action uses that decision.
A check-then-act race lets two withdrawals be approved using the same old balance before either changes it.
Chunk size
Chunk size is the number of input items grouped into one process-map batch, reducing the number of work messages for small tasks.
A larger chunk size can reduce process-map messages, but it has no batching effect on a thread pool.
Completion order
Completion order is the sequence in which calls finish, allowing an as_completed() loop to process ready outcomes before slower calls.
Completion order lets the reporting loop display a fast response while earlier submitted requests still wait.
Concurrency
Concurrency is the organization of several tasks whose lifetimes overlap, allowing progress by taking turns or running simultaneously.
Concurrency lets one core start another download while an earlier request is still waiting for its reply.
Concurrency limit
A concurrency limit bounds the number of operations active at the same time, protecting a resource from too many simultaneous users.
A request concurrency limit caps active connections but does not alone enforce a requests-per-second rule.
Cooperative multitasking
Cooperative multitasking lets tasks share execution by giving up control at suspension points, instead of being switched between arbitrary lines.
Cooperative multitasking keeps ordinary code between suspension points uninterrupted by tasks in the same loop.
Coordination overhead
Coordination overhead is time spent starting, scheduling, transferring, or synchronizing work instead of performing the useful independent computation.
Tiny process tasks can spend more time in coordination overhead than performing their useful calculations.
Coroutine function
A coroutine function is defined with async def and produces a coroutine object when called, leaving its body to be awaited or scheduled.
Calling a coroutine function such as fetch(name) creates an object without starting the network operation.
Coroutine object
A coroutine object is the paused computation created by calling an async function, retaining its local state as it runs and suspends.
Awaiting a coroutine object retrieves its value after the asynchronous operation finishes.
CPU-bound workload
A CPU-bound workload spends most of its time computing, so faster computation or independent work on additional cores can help.
A CPU-bound workload can keep a core busy with a pure-Python loop over data already in memory.
CPython
CPython is the usual implementation of Python; its standard build uses a GIL, while a separate free-threaded build can run without it.
CPython with its standard GIL active cannot spread pure-Python CPU threads across several cores.
Critical section
A critical section is code accessing shared state that must not interleave with a conflicting operation on that same state.
The critical section for a reservation includes its availability check and the matching stock decrement.

D

Daemon thread
A daemon thread is a background thread that does not keep Python alive and may be stopped abruptly when only daemon threads remain.
A daemon thread can monitor background activity, but required output needs a worker that finishes cleanly.
Done callback
A done callback is a function registered to run when a future completes or is cancelled, receiving the completed future as its argument.
A done callback can record progress, while the collection loop handles errors from each result.

E

Efficiency
Efficiency is speedup divided by worker count, relating the measured performance gain to how many workers were used for the job.
A speedup of 3 with four workers gives efficiency 0.75, usually reported as 75%.
Event
An event is a shared signaling flag that threads can set, clear, inspect, or wait for, often to request cooperative shutdown.
A worker waits on a stop event with a timeout so the main thread can end its pause early.
Event loop
An event loop coordinates ready async tasks and pending operations, running one task at a time in its thread until that task suspends.
A blocking file read occupies the event loop's thread and delays every other task using that loop.
Exception group
An exception group packages related failures into one raised object, allowing matching contained errors to be handled with except*.
An exception group reports ordinary child failures after the task group finishes cancellation cleanup.
Executor
An executor schedules submitted calls on reusable workers and provides a common interface for thread pools and process pools.
A caller can change executor type while retaining submit() and future-based result collection.
Exit code
An exit code records how a process ended: normal completion gives zero, an uncaught exception usually gives one, and POSIX signals give negatives.
A parent checks the child's exit code after joining instead of expecting a target function return value.

F

FIFO queue
A FIFO queue returns waiting items in the order they were added, allowing producers and consumers to exchange work through put() and get().
A FIFO queue supplies names in arrival order even though different workers can finish out of order.
Forkserver
Forkserver is a start method in which a separate server forks child processes, so children inherit server state rather than later parent state.
With forkserver, pass changed parent settings as arguments because children inherit the server's state.
Free-threaded build
A free-threaded build is a CPython build capable of executing Python threads on several cores while its GIL is disabled.
A free-threaded build may have its GIL enabled again after importing an incompatible extension module.
Future
A future represents one submitted call's eventual outcome, allowing the caller to inspect completion, retrieve a result, or receive its error.
Each report-reading future is saved before any result() call waits for one report.

G

Gather
Gather runs awaitables concurrently and collects their outcomes in argument order, with optional exception values instead of raised child errors.
Gather keeps a short request's result second in its list if that request was its second argument.
Global interpreter lock
The global interpreter lock (GIL) is a CPython lock allowing one thread at a time to execute bytecode while protecting interpreter internals.
The global interpreter lock is released during a blocking socket read, allowing another thread to execute.

I

I/O-bound workload
An I/O-bound workload spends most of its elapsed time waiting for external operations, such as network replies or storage access.
An I/O-bound workload may use only 0.2 s of CPU during a 10 s batch of remote storage reads.
Initializer
An initializer is a setup function run once in each worker when it starts, preparing reusable state before that worker handles calls.
An initializer loads a lookup table in each process once instead of repeating that setup for every call.
Input order
Input order is the sequence of submitted data, which executor map() preserves when yielding results even if calls finish differently.
Input order makes a slow first map call delay later completed results from the returned iterator.
Interpreter pool
An interpreter pool runs workers in isolated interpreters within one process, giving each interpreter its own GIL and serializing calls.
An interpreter pool can run CPU calls in parallel, but its imported extensions need compatible interpreter support.

L

Lost update
A lost update occurs when workers base changes on the same old value and a later write overwrites an update from another worker.
A lost update occurs when two threads both read 41 and both store 42 instead of reaching 43.

M

Main-module guard
The main-module guard is an if __name__ == "__main__": check that keeps script startup from running when the module is imported.
The main-module guard keeps pool creation from running again when a spawned child imports the script.
Manager proxy
A manager proxy is a local stand-in for an object owned by a manager server process, forwarding operations as messages to that server.
Frequent dictionary lookups through a manager proxy add communication to a worker's computation.
Mixed workload
A mixed workload has stages with different resource needs, such as network waiting followed by CPU-heavy analysis of the received data.
A mixed workload can download on an event loop and send expensive Python analysis to a process pool.
Mutual-exclusion lock
A mutual-exclusion lock permits one holder at a time, letting cooperating workers protect a shared logical operation from interleaving.
Every balance-changing path acquires the same mutual-exclusion lock for its full decision and update.

P

Parallelism
Parallelism is the execution of computations at the same instant on different CPU cores, allowing independent work to finish together.
Parallelism lets four processes analyze independent datasets at the same time on four available cores.
Partial result
A partial result is a worker's independent contribution that the parent combines with other contributions to form the complete answer.
The parent can add partial results from disjoint ranges when every intended input is counted exactly once.
Pending-call cancellation
Pending-call cancellation prevents an eligible submitted call from starting; future cancellation cannot stop a call already running.
Pending-call cancellation can discard eligible queued calls when a batch is no longer useful.
Pickling
Pickling serializes a Python object for storage or transfer; process-pool calls use it for functions, arguments, and returned results.
Pickling can transfer a file path to a worker, while an ordinary open file object is unsuitable.
Pipe
A pipe provides two communication endpoints for sending and receiving messages, offering a direct channel between the connected endpoints.
A parent receives a child's answer from one pipe endpoint after the child sends it through the other.
Process
A process is a running program with separate memory and an interpreter, allowing independent Python computation alongside other processes.
A child process changes its own ordinary list, so the parent needs an explicit message to get its results.
Process queue
A process queue transfers pickled messages between processes with synchronized put() and get() operations across their separate memory.
The parent drains a large result from the process queue before joining the child still flushing its output.
Producer-consumer pattern
The producer-consumer pattern organizes work around producers adding jobs to a queue and consumers repeatedly taking and handling them.
The producer-consumer pattern lets one reader supply records while a fixed team processes queued work.

R

Race condition
A race condition is a bug in which uncoordinated conflicting accesses make the outcome depend on how concurrent work interleaves.
A race condition can let two workers reserve the last item when both checks precede either stock update.
Rate limit
A rate limit restricts how many operations may occur during a time interval, requiring pacing that differs from a simultaneous-use limit.
A client respects a rate limit by pacing or rescheduling requests when the service reports HTTP 429.
Reentrant lock
A reentrant lock lets its owning thread acquire it repeatedly, requiring a matching release for each successful acquisition.
A reentrant lock supports a locked function calling another function that acquires the same thread-owned lock.
Result timeout
A result timeout limits how long a caller waits for a future's outcome without itself stopping the worker call that is still running.
A result timeout can expire while the request keeps running, so executor context exit may still wait.

S

Semaphore
A semaphore manages permits that limit how many workers may enter a guarded operation simultaneously, returning permits on exit.
A three-permit semaphore lets three connections operate while additional workers wait for access.
Sentinel
A sentinel is a reserved value placed among work items to signal a special action, such as asking one consumer to stop.
Four consumers need four stop sentinels so each worker can receive a message that ends its loop.
Sequential baseline
A sequential baseline is the reference run performing the same required work without overlapping workers, used for correctness and timing comparisons.
A sequential baseline uses the same inputs as a process-based version of a job and preserves meaningful duplicate outputs.
Shared value
A shared value is a typed object in shared memory that processes can access, with an associated lock available for compound operations.
Workers hold get_lock() while incrementing a shared value so its read and write stay together.
Shielding
Shielding prevents caller cancellation from passing through a particular await into inner work, while the caller still receives cancellation.
Shielding a save task still requires keeping its reference and awaiting it before loop shutdown.
Slow callback threshold
The slow callback threshold is the duration above which asyncio debug mode reports an event-loop callback or task step, normally 0.1 s.
The slow callback threshold helps debug logs flag a CPU loop that holds the event-loop thread too long.
Spawn
Spawn is a multiprocessing start method that launches a fresh child interpreter and imports the main module to locate its worker code.
With spawn, a top-level worker can be imported from the script, unlike a function defined only at a prompt.
Speedup
Speedup is sequential elapsed time divided by concurrent elapsed time for equivalent work, measuring how much faster the new version runs.
Reducing complete elapsed time from 12 s to 4 s gives speedup 3, so the new job takes one third as long.
Submission
Submission schedules a call for execution without waiting for its completion, letting the caller retain a future for later collection.
Submission with executor.submit(load, name) passes the function and argument without calling load in the caller.
Switch interval
The switch interval is CPython's requested interval for giving other threads a turn, with a usual value of 0.005 s.
The default switch interval requests a turn for other threads after 5 ms without fixing the switch location.

T

Target function
A target function is the callable a worker is configured to execute after it starts; its arguments are supplied separately.
Passing a function such as load as a target function delays its execution until the worker starts with the supplied arguments.
Task group
A task group owns related tasks, waits for their completion, and requests sibling cancellation when a child raises an ordinary failure.
An ordinary failure in one task group child requests cancellation of unfinished sibling operations.
Thread
A thread is an execution path with its own call stack inside a process, sharing that process's memory with its other threads.
Each thread can read the same fixed name list while writing its own prepared result slot.
Thread join
A thread join makes the calling thread wait for another thread to finish, optionally for a limited duration, and returns None.
After a timed thread join, the caller checks is_alive() to see whether the worker is still running.
Thread offloading
Thread offloading runs a blocking function in a worker thread while the coroutine awaits its outcome without occupying the event-loop thread.
Thread offloading with asyncio.to_thread() keeps connections responsive during a legacy blocking read.
Thread safety
Thread safety means concurrent thread accesses preserve the required program behavior through coordination or a design without conflicting writes.
A cache needs thread safety for its check-and-insert decision, even when individual container calls are protected.

U

Unretrieved task exception
An unretrieved task exception is a stored failure no code has obtained by awaiting the task or reading its completed outcome.
An ignored background task can leave an unretrieved task exception that is only logged when the task is collected.

W

Wall-clock time
Wall-clock time is the elapsed duration experienced by a caller, including computation, waiting, and the costs of managing workers.
Wall-clock time for a process job includes pool creation, child computation, result collection, and shutdown.
Worker pool
A worker pool is a fixed or bounded collection of reusable execution workers that handle many submitted jobs during a shared lifetime.
Reusing a worker pool avoids launching a fresh process interpreter for every small calculation.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started