On this page
  1. Concurrency and Parallelism
  2. Contents
  3. Choosing a Concurrency Model
  4. Asynchronous I/O (asyncio)
  5. Multithreading (threading & queue)
  6. Multiprocessing (multiprocessing & concurrent.futures)

Concurrency and Parallelism

Prev: Decorators and Closures | Up: Advanced Python Internals | Next: Memory Management and Internals
Rel: asyncio, threading, multiprocessing, concurrent, queue
Ref: docs.python.org — Concurrent Execution
Tags: #public #python3 #tutorials #internals #concurrency #asyncio #threading #multiprocessing


Contents


Choosing a Concurrency Model

Model Stdlib Module Execution Best For
Cooperative async asyncio Single-threaded event loop High-concurrency network/socket I/O
OS threads threading Shared memory, OS-scheduled Blocking I/O (disk, legacy C/socket APIs)
OS processes multiprocessing Separate Python interpreters CPU-bound parallel computation (bypasses GIL)
Unified pool API concurrent.futures Thread or process pools Simple map/submit fan-out workloads

Asynchronous I/O (asyncio)

[[stdlib_module/asyncio|asyncio]] multiplexes thousands of I/O-bound coroutines on a single thread using async def, await, and asyncio.TaskGroup (structured concurrency, Python 3.11+).

import asyncio

async def fetch_item(item_id: int, delay: float) -> str:
    await asyncio.sleep(delay)
    return f"item-{item_id}"

async def main() -> list[str]:
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch_item(i, 0.05)) for i in range(1, 4)]
    return [t.result() for t in tasks]

print(asyncio.run(main()))  # ['item-1', 'item-2', 'item-3']

Multithreading (threading & queue)

Use [[stdlib_module/queue|queue.Queue]] for thread-safe producer/consumer coordination and [[stdlib_module/threading|threading.Lock]] to protect shared mutable state.

import queue
import threading

work_q: queue.Queue[int | None] = queue.Queue()
results: list[int] = []
lock = threading.Lock()

def worker() -> None:
    while (item := work_q.get()) is not None:
        with lock:
            results.append(item * item)
        work_q.task_done()
    work_q.task_done()

t = threading.Thread(target=worker)
t.start()
for n in [2, 3, 4]:
    work_q.put(n)
work_q.put(None)
work_q.join()
t.join()
print(results)  # [4, 9, 16]

Multiprocessing (multiprocessing & concurrent.futures)

For CPU-bound work, spawn worker processes with [[stdlib_module/concurrent|concurrent.futures.ProcessPoolExecutor]] (or [[stdlib_module/multiprocessing|multiprocessing.Pool]]). Always guard process creation with if __name__ == "__main__": for cross-platform safety (macOS/Windows use spawn).

from concurrent.futures import ProcessPoolExecutor

def count_primes(limit: int) -> int:
    count = 0
    for n in range(2, limit):
        if all(n % d != 0 for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count

if __name__ == "__main__":
    with ProcessPoolExecutor() as pool:
        totals = list(pool.map(count_primes, [500, 1000, 1500]))
    print(totals)

Linked from

Related notes