Threading
The threading module starts OS threads that share the same process and memory. Use it for concurrent I/O. The GIL keeps CPU-bound Python from running in parallel.
Detailed Explanation
threading.Thread(target=func, args=(...)) wraps a function in a thread. start begins it. join waits for it. daemon=True lets the process exit without waiting; daemons are cut off mid-work, so use them for watchers, not for writes you must finish.
Threads share everything: lists, dicts, sockets, the import cache. That is the benefit and the hazard. A race is two threads interleaving a read-modify-write. counter += 1 is not atomic. Protect invariants with Lock, RLock, Event, Condition, or use queue.Queue so threads only pass messages.
ThreadPoolExecutor in concurrent.futures is the usual high-level API: submit callables, collect Futures. Raw Thread is for long-lived workers or when you need a custom lifecycle.
Do not call blocking threading primitives from asyncio tasks; you will stall the event loop. Do not use threads for CPU-bound Python; use processes. Do use threads for many network or disk waits, for wrapping blocking libraries, and for GUI apps that must keep a main thread responsive.
local() is thread-local storage: each thread sees its own attribute values. It is useful for per-request state and easy to leak if you do not clean it up.
Signals (including KeyboardInterrupt) are delivered to the main thread. A worker that loops forever without a stop event will keep the process alive after Ctrl-C unless it is a daemon or you join with a timeout and cancel.
Code Examples
import threading
results: list[str] = []
lock = threading.Lock()
def fetch(name: str) -> None:
with lock:
results.append(name)
workers = [threading.Thread(target=fetch, args=(n,)) for n in ("a", "b", "c")]
for w in workers:
w.start()
for w in workers:
w.join()
print(sorted(results)) # ['a', 'b', 'c']from concurrent.futures import ThreadPoolExecutor
def lookup(host: str) -> str:
return host.upper()
with ThreadPoolExecutor(max_workers=4) as pool:
print(list(pool.map(lookup, ["db", "cache"]))) # ['DB', 'CACHE']Common Gotchas
Mutating a list or dict from two threads without a lock
you can lose updates or crash with `RuntimeError: dictionary changed size`.
Daemon threads die with the process
a daemon mid-`write` can leave a truncated file. Join workers that must finish.
`join` in the thread you are joining with
deadlock. Do not make a thread wait on itself.
The GIL serialises bytecode, not your algorithm
I/O overlaps; `balance -= 1` still needs a lock.