Threading
In one line
threading runs multiple threads in one process — good for I/O-bound work, limited for CPU-bound due to GIL.
In simple words
Python's threading module lets you run multiple threads within a single process. Threads share memory, making data sharing easy but requiring locks to avoid races.
Due to the GIL, only one thread executes Python bytecode at a time. This means threading does NOT speed up CPU-bound work. However, the GIL is released during I/O operations (file, network, sleep), so threading IS effective for I/O-bound tasks.
Use threading.Thread to create threads, threading.Lock for mutual exclusion, and concurrent.futures.ThreadPoolExecutor for a high-level pool API.
Example
import threading
import time
results = []
lock = threading.Lock()
def worker(n):
time.sleep(0.5) # Simulates I/O
with lock:
results.append(n)
threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Results: {sorted(results)}") # [0, 1, 2, 3, 4]Threads run concurrently. The lock protects shared 'results' list from race conditions. GIL is released during sleep.
Common confusions
Confused with: multiprocessing
The difference: threading shares memory (easy data sharing, but needs locks) and is limited by GIL for CPU work. multiprocessing uses separate memory (no GIL, true parallelism) but requires serialization to share data. Use threading for I/O, multiprocessing for CPU.
Related terms
Related Resources
Related Lessons
- Python Concurrency
Threading.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.