On this page
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
- > Asynchronous I/O (`asyncio`)
- > Multithreading (`threading` & `queue`)
- > Multiprocessing (`multiprocessing` & `concurrent.futures`)
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
- tuts/programming/concurrency
- tuts/programming/concurrency/concurrency_vs_parallelism
- tuts/python3/tutorials
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals
Related notes
- tuts/python3/tutorials/advanced_python_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/programming/concurrency links to this page; shared tags: #concurrency
- tuts/programming/concurrency/concurrency_vs_parallelism links to this page; shared tags: #concurrency
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/python3/stdlib_module/asyncio Linked here
- tuts/python3/stdlib_module/concurrent Linked here
- tuts/python3/stdlib_module/multiprocessing Linked here
- tuts/python3/stdlib_module/queue Linked here