thread
In Python, a thread is an independent flow of execution within a single process. With threads, a program can make progress on multiple tasks concurrently. For example, keeping a user interface (UI) responsive while performing network requests in the background.
Threads are often most helpful for I/O-bound tasks or high-latency work, such as file operations, network calls, or waiting on external services where they can improve responsiveness and overall throughput.
Python’s standard library includes the threading module, which provides tools for creating, coordinating, and managing threads.
One important caveat when using threads in CPython is the Global Interpreter Lock (GIL). The GIL ensures that only one thread executes Python bytecode at a time, which means threads typically don’t speed up CPU-bound tasks. Python 3.13 introduced an experimental free-threaded build that lets you disable the GIL for true parallel execution, and Python 3.14 promoted this build to officially supported status (PEP 703, PEP 779).
Example
Here’s a quick example of how to create and use a thread in Python:
>>> import threading
>>> import time
>>> def print_numbers():
... for i in range(5):
... print(i)
... time.sleep(1)
...
>>> # Create a thread
>>> thread = threading.Thread(target=print_numbers)
>>> # Start the thread
>>> thread.start()
>>> # Main thread continues to run concurrently
>>> for i in range(5, 10):
... print(i)
... time.sleep(1)
...
>>> # Wait for the worker thread to finish
>>> thread.join()
0
5
1
6
2
7
3
8
4
9
In this example, print_numbers() runs in a separate thread while the main thread prints its own numbers. The output from both threads will interleave, demonstrating concurrent execution. Note that the exact output order may vary between runs because thread scheduling is non-deterministic.
Related Resources
Tutorial
Python Thread Safety: Using a Lock and Other Techniques
In this tutorial, you'll learn about the issues that can occur when your code is run in a multithreaded environment. Then you'll explore the various synchronization primitives available in Python's threading module, such as locks, which help you make your code safe.
For additional information on related topics, take a look at the following resources:
- Thread Safety in Python: Locks and Other Techniques (Course)
- An Intro to Threading in Python (Tutorial)
- Python 3.13: Free Threading and a JIT Compiler (Tutorial)
- Speed Up Your Python Program With Concurrency (Tutorial)
- Threading in Python (Course)
- Python Thread Safety: Using a Lock and Other Techniques (Quiz)
- Python Threading (Quiz)
- Python 3.13: Free Threading and a JIT Compiler (Quiz)
- Speed Up Python With Concurrency (Course)
- Python Concurrency (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.