Robots Atlas>ROBOTS ATLAS

Python — From Basics to Advanced · Concurrency II — Threads, Processes, GIL

threading — Threads and Synchronization

Concurrency II — Threads, Processes, GIL

Introduction

The threading module is the high-level API for system threads. It provides the Thread class, synchronization primitives (Lock, RLock, Semaphore, Event, Condition, Barrier), and thread-local storage (local()). Threads share memory — a strength (zero serialization) and a risk (race conditions, deadlocks).

In CPython with the GIL, threading is a tool for I/O concurrency, not parallel CPU. Typical patterns: producer-consumer with queue.Queue (which already has built-in locks), a thread pool fetching URLs, a parallel file scanner. Daemon threads (daemon=True) terminate automatically when main exits — useful for background tasks.

Synchronization: Lock is a mutex (one thread), RLock is a re-entrant mutex (the same thread may acquire repeatedly), Semaphore(n) is a counter (max N threads), Event is a flag (set/clear/wait), Condition provides wait/notify for complex scenarios, Barrier(n) synchronizes N threads at a point. Always use with lock: instead of manual acquire/release.