On this page
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
- Always acquire locks with
with lock:: Manuallock.acquire()/lock.release()deadlocks if an exception is raised beforerelease(). - Avoid
daemon=Truefor threads that write files or hold resources: Daemon threads are killed abruptly at interpreter exit without runningfinallyblocks; use athreading.Event+.join(). - Pass work between threads via
queue.Queue, not shared lists:queue.Queuehandles locking and backpressure safely. - Acquire multiple locks in a consistent global order to prevent deadlocks.
Common Functions
- threading.active_count() —
active_count()— Return the number of Thread objects currently alive. - threading.current_thread() —
current_thread()— Return the current Thread object, corresponding to the caller's thread of control. - threading.enumerate() —
enumerate()— Return a list of all Thread objects currently alive. - threading.excepthook() —
excepthook(args, /)— Handle uncaught Thread.run() exception. - threading.get_ident() —
get_ident()— Return a non-zero integer that uniquely identifies the current thread amongst other threads that exist simultaneously. - threading.get_native_id() —
get_native_id()— Return a non-negative integer identifying the thread as reported by the OS (kernel). This may be used to uniquely identify a particular thread within a system. - threading.getprofile() —
getprofile()— Get the profiler function as set by threading.setprofile(). - threading.gettrace() —
gettrace()— Get the trace function as set by threading.settrace(). - threading.main_thread() —
main_thread()— Return the main thread object. - threading.RLock() —
RLock(*args, **kwargs)— Factory function that returns a new reentrant lock. - threading.setprofile() —
setprofile(func)— Set a profile function for all threads started from the threading module. - threading.setprofile_all_threads() —
setprofile_all_threads(func)— Set a profile function for all threads started from the threading module and all Python threads that are currently executing. - threading.settrace() —
settrace(func)— Set a trace function for all threads started from the threading module. - threading.settrace_all_threads() —
settrace_all_threads(func)— Set a trace function for all threads started from the threading module and all Python threads that are currently executing. - threading.stack_size() —
stack_size(size=0, /)— Return the thread stack size used when creating new threads. The optional size argument specifies the stack size (in bytes) to be used for subsequently created threads, and must be 0 (use platform or
Classes & Objects
- threading.Barrier — Implements a Barrier. (Methods:
.abort(),.broken(),.n_waiting(),.parties(),.reset(),.wait()) - threading.BoundedSemaphore — Implements a bounded semaphore. (Methods:
.acquire(),.release()) - threading.BrokenBarrierError —
threading.BrokenBarrierErrorclass. (Methods:.add_note(),.with_traceback()) - threading.Condition — Class that implements a condition variable. (Methods:
.notify(),.notifyAll(),.notify_all(),.wait(),.wait_for()) - threading.Event — Class implementing event objects. (Methods:
.clear(),.isSet(),.is_set(),.set(),.wait()) - threading.ExceptHookArgs — ExceptHookArgs Type used to pass arguments to threading.excepthook. (Methods:
.count(),.index()) - threading.local — Thread-local data
- threading.Lock — A lock object is a synchronization primitive. To create a lock, call threading.Lock(). Methods are: acquire() -- lock the lock, possibly blocking until it can be obtained (Methods:
.acquire(),.acquire_lock(),.locked(),.locked_lock(),.release(),.release_lock()) - threading.Semaphore — This class implements semaphore objects. (Methods:
.acquire(),.release()) - threading.Thread — A class that represents a thread of control. (Methods:
.daemon(),.getName(),.ident(),.isDaemon(),.is_alive(),.join()) - threading.ThreadError — Unspecified run-time error. (Methods:
.add_note(),.with_traceback()) - threading.Timer — Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() (Methods:
.cancel(),.daemon(),.getName(),.ident(),.isDaemon(),.is_alive())
Constants & Attributes
threading.TIMEOUT_MAX(float) =9223372036.0
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/asyncio
- tuts/python3/stdlib_module/concurrent
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/multiprocessing
- tuts/python3/stdlib_module/queue
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/this
- tuts/python3/stdlib_module/threading/active_count
- tuts/python3/stdlib_module/threading/Barrier
- tuts/python3/stdlib_module/threading/BoundedSemaphore
- tuts/python3/stdlib_module/threading/BrokenBarrierError
- tuts/python3/stdlib_module/threading/Condition
- tuts/python3/stdlib_module/threading/current_thread
- tuts/python3/stdlib_module/threading/enumerate
- tuts/python3/stdlib_module/threading/Event
- tuts/python3/stdlib_module/threading/excepthook
- tuts/python3/stdlib_module/threading/ExceptHookArgs
- tuts/python3/stdlib_module/threading/get_ident
- tuts/python3/stdlib_module/threading/get_native_id
- tuts/python3/stdlib_module/threading/getprofile
- tuts/python3/stdlib_module/threading/gettrace
- tuts/python3/stdlib_module/threading/local
- tuts/python3/stdlib_module/threading/Lock
- tuts/python3/stdlib_module/threading/main_thread
- tuts/python3/stdlib_module/threading/RLock
- tuts/python3/stdlib_module/threading/Semaphore
- tuts/python3/stdlib_module/threading/setprofile
- tuts/python3/stdlib_module/threading/setprofile_all_threads
- tuts/python3/stdlib_module/threading/settrace
- tuts/python3/stdlib_module/threading/settrace_all_threads
- tuts/python3/stdlib_module/threading/stack_size
- tuts/python3/stdlib_module/threading/Thread
- tuts/python3/stdlib_module/threading/ThreadError
- tuts/python3/stdlib_module/threading/Timer
- tuts/python3/stdlib_module/time
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism
- tuts/python3/tutorials/popular_application_domains/desktop_gui_development
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/this Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/active_count Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/Barrier Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/BoundedSemaphore Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/BrokenBarrierError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/Condition Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/current_thread Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/enumerate Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/Event Linked here; links to this page; shared tags: #stdlib