Last Updated on September 12, 2022
You can get the main thread for a process via the threading.main_thread() function.
In this tutorial you will discover how to get the main thread for a process in Python.
Let’s get started.
Need To Get Process Main Thread
A process is a running instance of a computer program.
Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create new child processes in our program in order to execute code concurrently.
Python provides the ability to create and manage new processes via the multiprocessing.Process class.
In multiprocessing, we may need to get the main thread of a process.
This may be for many reasons, such as:
- Logging the details of the process and thread.
- Conditionally execute code based on the thread that is running.
- Send messages or signals between threads within a process.
What is the main thread and how can we get the main thread of a process?
Run loops using all CPUs, download your FREE book to learn how.
What is the Main Thread
Each Python process is created with one thread called the main thread.
This thread has the distinct name ‘MainThread‘, although thread names can be changed.
The main thread can be thought of as the default thread within a Python process.
There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.
— threading — Thread-based parallelism
How to Get The Main Thread
We can get the main thread of a process via the threading.main_thread() function.
For example:
1 2 3 |
... # get the main thread thread = threading.main_thread() |
Each process in your Python program will have its own main thread.
This means that if you have multiple child processes, each child process will have its own main thread.
The function must be called within the process for which you want to access the main thread. You cannot get the main thread for another process, at least not directly.
The threading.main_thread() function for getting the main thread can be called within the main process or within a child process.
You can learn more about the main thread in the tutorial:
Now that we know how to access the main thread, let’s look at some worked examples.
Free Python Multiprocessing Course
Download your FREE multiprocessing PDF cheat sheet and get BONUS access to my free 7-day crash course on the multiprocessing API.
Discover how to use the Python multiprocessing module including how to create and start child processes and how to use a mutex locks and semaphores.
Get the Main Thread for the Main Process
We can get the main thread of the main process.
In this example we first report the details of the main process, then get the main thread for the main process and report its details.
The complete example is listed below.
1 2 3 4 5 6 7 8 9 10 |
# SuperFastPython.com # example of getting the main thread of the main process from multiprocessing import current_process from threading import main_thread # get the current process process = current_process() # get the main thread for the main process thread = main_thread() # report details print(f'Process: {process.name}, main thread: {thread}') |
Running the example first gets the multiprocessing.Process instance for the main process.
It then gets the threading.Thread instance for the main thread for the main process.
It then reports the name of the main process and the details of the main thread.
1 |
Process: MainProcess, main thread: <_MainThread(MainThread, started 4633234944)> |
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
Get the Main Thread for Child Processes
We can get the main thread of a child process.
In this example we create child processes to execute a custom function. Within each child process, we get the details of the process itself, then get the main thread of the process. This is a different main thread from the main thread in the main process.
First we can define a function to execute in a new child process.
The function will first get the process instance for the current process, then the thread instance for the main thread. It then reports the name of the process and the details of the main thread.
The task() function below implements this.
1 2 3 4 5 6 7 8 |
# function executed in child processes def task(): # get the current process process = current_process() # get the main thread for the main process thread = main_thread() # report details print(f'Process: {process.name}, main thread: {thread}', flush=True) |
Next, in the main process, we will create five child processes, each configured to execute the custom function. This can be achieved in a list comprehension.
We then start the child processes, then wait for them to terminate.
1 2 3 4 5 6 7 8 9 10 |
# protect the entry point if __name__ == '__main__': # create child processes children = [Process(target=task) for _ in range(5)] # start child processes for child in children: child.start() # wait for children processes to terminate for child in children: child.join() |
Tying this together, the complete example is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# SuperFastPython.com # example of getting the main thread for child processes from multiprocessing import current_process from multiprocessing import Process from threading import main_thread # function executed in child processes def task(): # get the current process process = current_process() # get the main thread for the main process thread = main_thread() # report details print(f'Process: {process.name}, main thread: {thread}', flush=True) # protect the entry point if __name__ == '__main__': # create child processes children = [Process(target=task) for _ in range(5)] # start child processes for child in children: child.start() # wait for children processes to terminate for child in children: child.join() |
Running the example first creates and starts five child processes to execute our custom function.
The main process then blocks, waiting for the child processes to terminate.
Each child process then gets the process instance for itself and the thread instance for the main thread. It then reports the process name and the details of its main thread.
1 2 3 4 5 |
Process: Process-1, main thread: <_MainThread(MainThread, started 4565982720)> Process: Process-2, main thread: <_MainThread(MainThread, started 4536012288)> Process: Process-3, main thread: <_MainThread(MainThread, started 4443872768)> Process: Process-4, main thread: <_MainThread(MainThread, started 4492758528)> Process: Process-5, main thread: <_MainThread(MainThread, started 4460502528)> |
Further Reading
This section provides additional resources that you may find helpful.
Python Multiprocessing Books
- Python Multiprocessing Jump-Start, Jason Brownlee (my book!)
- Multiprocessing API Interview Questions
- Multiprocessing API Cheat Sheet
I would also recommend specific chapters in the books:
- Effective Python, Brett Slatkin, 2019.
- See: Chapter 7: Concurrency and Parallelism
- High Performance Python, Ian Ozsvald and Micha Gorelick, 2020.
- See: Chapter 9: The multiprocessing Module
- Python in a Nutshell, Alex Martelli, et al., 2017.
- See: Chapter: 14: Threads and Processes
Guides
- Python Multiprocessing: The Complete Guide
- Python Multiprocessing Pool: The Complete Guide
- Python ProcessPoolExecutor: The Complete Guide
APIs
References
Takeaways
You now know how to get the main thread for a process.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Samule Sun on Unsplash
Do you have any questions?