Skip to main content

Lib/threading.py

cpython 3.14 @ ab2d84fe1023/Lib/threading.py

Lib/threading.py builds the high-level threading API on top of _thread (a C extension that wraps OS threads). It provides Thread, the synchronisation primitives, and the local() thread-local storage class.

Map​

LinesSymbolRole
1-200Lock, RLockThin wrappers around _thread.lock / _thread.RLock
201-450Condition, Semaphore, BoundedSemaphore, Event, BarrierHigher-level synchronisation
451-900ThreadThread lifecycle, start/run/join/daemon
901-1100TimerDelayed callback thread
1101-1300localThread-local storage via _threading_local
1301-1500current_thread, enumerate, main_thread, settrace, setprofileIntrospection

Reading​

Thread.start and the _bootstrap wrapper​

Thread.start() calls _thread.start_new_thread(self._bootstrap, ()). _bootstrap calls _bootstrap_inner inside a try/except that catches all exceptions, stores unhandled ones in self._exc_info, and calls the excepthook if set.

# CPython: Lib/threading.py:960 Thread.start
def start(self):
with _active_limbo_lock:
_limbo[self] = self
try:
_start_new_thread(self._bootstrap, ())
except Exception:
...
self._started.wait()

Condition and wait​

Condition.wait(timeout) releases the underlying lock, registers the calling thread's Event with the waiter list, and blocks on the event. notify() pops one waiter and sets its event. notify_all() sets all waiters.

Barrier​

Barrier(parties) blocks each calling thread until parties threads have called barrier.wait(). Then all are released simultaneously. A broken barrier raises BrokenBarrierError in all waiting threads.

local​

threading.local() returns an object whose attribute accesses go through _local.__getattribute__ which dispatches to a per-thread dict stored in _thread._local. Each thread gets an independent namespace.

gopy notes​

Not yet ported. threading.Thread will map to goroutines in module/threading/. Lock maps to sync.Mutex, RLock to sync.RWMutex, Condition to sync.Cond, Event to a channel. local() maps to goroutine-local context.