On this page
  1. threading
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Cooperative Shutdown with threading.Event
  7. 2. Thread-Local State with threading.local()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

threading

Prev: this | Up: stdlib_module | Next: time
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — threading
Tags: #public #python3 #stdlib


Import

import threading

Overview

OS-level thread creation and synchronization primitives (Thread, Lock, RLock, Event, Condition, Semaphore, Barrier, local). Ideal for blocking synchronous I/O (network calls, disk waits, C extensions that release the GIL); for fan-out work batches prefer concurrent.futures.ThreadPoolExecutor, and for CPU-bound pure Python prefer multiprocessing (or free-threaded Python).

Quick Start

import threading

counter = 0
lock = threading.Lock()

def bump(n: int) -> None:
    global counter
    for _ in range(n):
        with lock:
            counter += 1

threads = [threading.Thread(target=bump, args=(1000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
assert counter == 4000

Implementation Walkthrough

1. Cooperative Shutdown with threading.Event

Never try to kill a thread abruptly; signal it cleanly with an Event so it can release locks and flush state:

import threading

def worker(stop_event: threading.Event, out: list[str]) -> None:
    while not stop_event.is_set():
        out.append("tick")
        stop_event.wait(timeout=0.05)  # wakes immediately when .set() is called

stop = threading.Event()
log: list[str] = []
t = threading.Thread(target=worker, args=(stop, log))
t.start()
stop.set()
t.join(timeout=2.0)
assert len(log) >= 1

2. Thread-Local State with threading.local()

Keep per-thread resources (such as sqlite3 connections) isolated without passing them through every function call:

import threading

tls = threading.local()
tls.request_id = "req-42"
assert tls.request_id == "req-42"

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes