Skip to main content

Concurrency with `threading`

Standard Library

threading Module Guide

Threads shine for I/O-bound workloads: API calls, file operations, and background tasks. Learn the primitives you need to stay safe.

Basics

import threading

def worker(order_id):
process(order_id)

threads = [
threading.Thread(target=worker, args=(oid,))
for oid in order_ids
]
for t in threads:
t.start()
for t in threads:
t.join()

Synchronization primitives

PrimitivePurpose
Lock / RLockMutual exclusion around shared state
EventSignal between threads
SemaphoreLimit concurrency
ConditionWait for state changes
QueueThread-safe producer/consumer communication

Prefer queue.Queue for coordinating work—no explicit locking required.

When not to use threads

  • CPU-bound tasks are limited by the GIL; use multiprocessing or native extensions instead.
  • Threads add complexity—profile before introducing them.

Next up in your learning path