threading
The Python threading
module provides a higher-level interface for working with threads, allowing you to run multiple operations concurrently within the same process.
It simplifies the management of threads, making it easier to write concurrent applications in Python.
Here’s a quick example:
>>> import threading
>>> def greet():
... print("Hello, World!")
...
>>> thread = threading.Thread(target=greet)
>>> thread.start()
>>> thread.join()
Hello, World!
Key Features
- Creates and manages threads for concurrent execution
- Synchronizes operations across multiple threads
- Provides thread-safe data structure and synchronization primitives
- Supports background processing
- Offers thread-local storage for per-thread data
- Enables naming and identification of threads
- Coordinates execution using events and condition variables
- Detects and manages active threads within the process
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
threading.Thread |
Class | Represents a single thread of control |
threading.Lock |
Class | Implements a basic lock (mutex) |
threading.RLock |
Class | Implements a reentrant lock that can be acquired multiple times by the same thread |
threading.Event |
Class | Provides a mechanism for communicating between threads |
threading.Condition |
Class | Provides thread synchronization via a condition variable |
threading.Semaphore |
Class | Limits access to a shared resource |
threading.active_count() |
Function | Returns the number of currently active threads |
threading.current_thread() |
Function | Returns the current Thread object |
Examples
Creating and starting a thread:
>>> import threading
>>> def print_numbers():
... for i in range(5):
... print(i)
...
>>> thread = threading.Thread(target=print_numbers)
>>> thread.start()
>>> thread.join()
0
1
2
3
4
Using a lock to synchronize threads:
>>> lock = threading.Lock()
>>> def thread_safe_increment(counter):
... with lock:
... counter[0] += 1
...
>>> counter = [0]
>>> threads = [
... threading.Thread(target=thread_safe_increment, args=(counter,))
... for _ in range(10)
... ]
>>> for thread in threads:
... thread.start()
...
>>> for thread in threads:
... thread.join()
...
>>> counter[0]
10
Common Use Cases
- Running I/O-bound tasks concurrently
- Managing access to shared resources with locks and semaphores
- Coordinating task execution using events and condition variables
- Performing background or periodic tasks in applications
- Improving user interface responsiveness by offloading work to threads
- Isolating data for each thread with thread-local storage
- Executing parallel operations for faster data processing
- Simulating concurrent scenarios for testing and development
Real-World Example
In the example below, you’ll demonstrate how to download multiple web pages concurrently using threads:
>>> import threading, requests
>>> urls = [
... "https://www.example.com",
... "https://www.python.org",
... "https://www.realpython.com"
... ]
>>> def fetch_url(url):
... response = requests.get(url)
... print(f"{url}: {response.status_code}")
...
>>> threads = [
... threading.Thread(target=fetch_url, args=(url,))
... for url in urls
... ]
>>> for thread in threads:
... thread.start()
...
>>> for thread in threads:
... thread.join()
...
https://www.example.com: 200
https://www.python.org: 200
https://www.realpython.com: 200
In this example, the threading
module allows you to fetch multiple web pages concurrently. This significantly reduces the total time required compared to fetching them sequentially or synchronously.
Related Resources
Tutorial
An Intro to Threading in Python
In this intermediate-level tutorial, you'll learn how to use threading in your Python programs. You'll see how to create threads, how to coordinate and synchronize them, and how to handle common problems that arise in threading.
For additional information on related topics, take a look at the following resources:
- Threading in Python (Course)
- Python Threading (Quiz)
By Leodanis Pozo Ramos • Updated July 24, 2025