Last Updated on September 12, 2022
You can access the threads in a Python program using threading module functions.
In this tutorial you will discover how to access and query threads in Python using thread utility functions.
Let’s get started.
Need Thread Utility Functions
A thread is a thread of execution in a computer program.
Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create additional threads in our program in order to execute code concurrently.
Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.
In some applications we may have many threads and may need to access details about the number of threads that are running or access properties of threading.Thread instances for specific threads.
How can we get access to the threads in a Python program?
Run loops using all CPUs, download your FREE book to learn how.
How to Use Thread Utility Functions
There are a number of utilities we can use when working with threads within a Python process.
These utilities are provided as “threading” module functions.
Examples of popular threading module utility functions are as follows:
- active_count(): Returns an integer count of the number of running threads.
- current_thread(): Returns a threading.Thread instance for the current thread.
- main_thread(): Returns a threading.Thread instance for the main thread.
- get_ident(): Returns the thread identifier integer assigned by the Python interpreter.
- get_native_id(): Returns the native thread identifier integer assigned by the operating system.
- enumerate(): Returns a list of threading.Thread instances that are currently running.
Some additional threading module functions that are less commonly used include the following:
- excepthook(): Set the exception handling function for all threads.
- settrace() and gettrace(): Set and get the trace function for all threads.
- setprofile() and getprofile(): Set and get the profile function for all threads.
- stack_size(): Set and get the default stack size used for new threads.
Now that we are familiar with the threading module functions, let’s look at some worked examples.
How to Get The Number of Active Threads
We can discover the number of active threads in a Python process.
This can be achieved via the threading.active_count() function that returns an integer that indicates the number threads that are “alive“.
1 2 3 |
... # get the number of active threads count = active_count() |
We can demonstrate this with a short example.
1 2 3 4 5 6 7 |
# SuperFastPython.com # report the number of active threads from threading import active_count # get the number of active threads count = active_count() # report the number of active threads print(count) |
Running the example reports the number of active threads in the process.
Given that there is only a single thread, the main thread, the count is one.
1 |
1 |
Free Python Threading Course
Download your FREE threading PDF cheat sheet and get BONUS access to my free 7-day crash course on the threading API.
Discover how to use the Python threading module including how to create and start new threads and how to use a mutex locks and semaphores
How to Get The Current Thread
We can get a threading.Thread instance for the thread running the current code.
This can be achieved via the threading.current_thread() function that returns a threading.Thread instance.
1 2 3 |
... # get the current thread thread = current_thread() |
We can demonstrate this with a short example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# SuperFastPython.com # retrieve the current thread from threading import Thread from threading import current_thread # function to get the current thread def task(): # get the current thread thread = current_thread() # report the name print(thread.name) # create a thread thread = Thread(target=task) # start the thread thread.start() # wait for the thread to exit thread.join() |
Running the example first creates a new threading.Thread to run a custom function.
The custom function acquires a threading.Thread instance for the currently running thread and uses it to report the name of the currently running thread.
1 |
Thread-1 |
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
How to Get The Main Thread
We can get a threading.Thread instance for the main thread of the Python process.
You may recall that each Python process has a default thread used to execute our code, referred to as the main thread and assigned the name “MainThread“.
A threading.Thread instance for the main thread can be acquired via the threading.main_thread() function.
1 2 3 |
... # get the main thread thread = main_thread() |
We can demonstrate this with a short example.
1 2 3 4 5 6 7 |
# SuperFastPython.com # example of getting the main thread from threading import main_thread # get the main thread thread = main_thread() # report the name of the main thread print(thread.name) |
Running the example first gets a threading.Thread instance that represents the main thread then reports the name attribute of the thread.
1 |
MainThread |
How to Get The Thread Identifier
We can get the Python thread identifier for the current thread.
This can be achieved via the threading.get_ident() function.
1 2 3 |
... # get the id for the current thread identifier = get_ident() |
Recall that each thread within a Python process has a unique identifier assigned by the interpreter.
We can demonstrate this with a short example.
1 2 3 4 5 6 7 |
# SuperFastPython.com # report the id for the current thread from threading import get_ident # get the id for the current thread identifier = get_ident() # report the thread id print(identifier) |
Running the example gets and reports the identifier of the currently running thread.
Note, your identifier will differ as a new identifier is assigned to a thread each time the code is run.
1 |
4662242816 |
How to Get The Native Thread Identifier
We can get the native thread identifier for the current thread assigned by the operating system.
This can be achieved via the threading.get_native_id() function.
1 2 3 |
... # get the native id for the current thread identifier = get_native_id() |
Recall that each thread within a Python process has a unique native identifier assigned by the operating system.
We can demonstrate this with a short example.
1 2 3 4 5 6 7 |
# SuperFastPython.com # report the native id for the current thread from threading import get_native_id # get the native id for the current thread identifier = get_native_id() # report the thread id print(identifier) |
Running the example gets and reports the native identifier of the currently running thread.
Note, your native identifier will differ as a new identifier is assigned to a thread each time the code is run.
1 |
374772 |
How to Enumerate Active Threads
We can get a list of all active threads within a Python process.
This can be achieved via the threading.enumerate() function.
1 2 3 |
... # get a list of all active threads threads = threading.enumerate() |
Only those threads that are “alive” will be included in the list, meaning those threads that are currently executing their run() function.
The list will always include the main thread.
We can demonstrate this with a short example.
1 2 3 4 5 6 7 8 |
# SuperFastPython.com # enumerate all active threads import threading # get a list of all active threads threads = threading.enumerate() # report the name of all active threads for thread in threads: print(thread.name) |
Running the example first retrieves a list of all active threads within the Python process.
The list of active threads is then iterated, reporting the name of each thread. In this case, the list only includes the main thread.
1 |
MainThread |
Further Reading
This section provides additional resources that you may find helpful.
Python Threading Books
- Python Threading Jump-Start, Jason Brownlee (my book!)
- Threading API Interview Questions
- Threading Module API Cheat Sheet
I also recommend specific chapters in the following books:
- Python Cookbook, David Beazley and Brian Jones, 2013.
- See: Chapter 12: Concurrency
- Effective Python, Brett Slatkin, 2019.
- See: Chapter 7: Concurrency and Parallelism
- Python in a Nutshell, Alex Martelli, et al., 2017.
- See: Chapter: 14: Threads and Processes
Guides
- Python Threading: The Complete Guide
- Python ThreadPoolExecutor: The Complete Guide
- Python ThreadPool: The Complete Guide
APIs
References
Takeaways
You now know how to use thread utility functions in Python.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Daniel Thürler on Unsplash
Do you have any questions?