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
| Primitive | Purpose |
|---|---|
Lock / RLock | Mutual exclusion around shared state |
Event | Signal between threads |
Semaphore | Limit concurrency |
Condition | Wait for state changes |
Queue | Thread-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.