Last Updated on September 12, 2022
You can run a function in a new thread via the “target” argument on the threading.Thread class.
In this tutorial you will discover how to run a function in a new thread.
Let’s get started.
Need to Run A Function in a New Thread
A thread is a thread of execution in a computer program.
Every Python program has at least one thread of execution referred to as 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.Thread class.
One way of running a function in a new thread is via an argument on the threading.Thread class.
How can we run a function in a new thread using the threading.Thread class?
Run loops using all CPUs, download your FREE book to learn how.
How to Run a Function In a Thread
To run a function in another thread:
- Create an instance of the threading.Thread class.
- Specify the name of the function via the “target” argument.
- Call the start() function.
First, we must create a new instance of the threading.Thread class and specify the function we wish to execute in a new thread via the “target” argument.
1 2 3 |
... # create a thread thread = Thread(target=task) |
The function executed in another thread may have arguments in which case they can be specified as a tuple and passed to the “args” argument of the threading.Thread class constructor or as a dictionary to the “kwargs” argument.
1 2 3 |
... # create a thread thread = Thread(target=task, args=(arg1, arg2)) |
We can then start executing the thread by calling the start() function.
The start() function will return immediately and the operating system will execute the function in a separate thread as soon as it is able.
1 2 3 |
... # run the thread thread.start() |
And that’s all there is to it.
We do not have control over when the thread will execute precisely or which CPU core will execute it. Both of these are low-level responsibilities that are handled by the underlying operating system.
Next, let’s look at a worked example of executing a function in a new thread.
Example of Running a Function in a Thread
First, we can define a custom function that will be executed in another thread.
We will define a simple function that blocks for a moment then prints a statement.
The function can have any name we like, in this case we’ll name it “task“.
1 2 3 4 5 6 |
# a custom function that blocks for a moment def task(): # block for a moment sleep(1) # display a message print('This is from another thread') |
Next, we can create an instance of the threading.Thread class and specify our function name as the “target” argument in the constructor.
1 2 3 |
... # create a thread thread = Thread(target=task) |
Once created we can run the thread which will execute our custom function in a new native thread, as soon as the operating system can.
1 2 3 |
... # run the thread thread.start() |
The start() function does not block, meaning it returns immediately.
We can explicitly wait for the new thread to finish executing by calling the join() function. This is not needed as the main thread will not exit until the new thread has completed but does make things clearer.
1 2 3 4 |
... # wait for the thread to finish print('Waiting for the thread...') thread.join() |
Tying this together, the complete example of executing a function in another thread is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# SuperFastPython.com # example of running a function in another thread from time import sleep from threading import Thread # a custom function that blocks for a moment def task(): # block for a moment sleep(1) # display a message print('This is from another thread') # create a thread thread = Thread(target=task) # run the thread thread.start() # wait for the thread to finish print('Waiting for the thread...') thread.join() |
Running the example first creates the threading.Thread then calls the start() function. This does not start the thread immediately, but instead allows the operating system to schedule the function to execute as soon as possible.
The main thread then prints a message waiting for the thread to complete, then calls the join() function to explicitly block and wait for the new thread to finish executing.
Once the custom function returns, the thread is closed. The join() function then returns and the main thread exits.
1 2 |
Waiting for the thread... This is from another thread |
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
Example of Running a Function in a Thread With Arguments
We can execute functions in another thread that take arguments.
This can be demonstrated by first updating our task() function from the previous section to take two arguments, one for the time in seconds to block and the second for a message to display.
1 2 3 4 5 6 |
# a custom function that blocks for a moment def task(sleep_time, message): # block for a moment sleep(sleep_time) # display a message print(message) |
Next, we can update the call to the threading.Thread constructor to specify the two arguments in the order that our task() function expects them as a tuple via the “args” argument.
1 2 3 |
... # create a thread thread = Thread(target=task, args=(1.5, 'New message from another thread')) |
Tying this together, the complete example of executing a custom function that takes arguments in a separate thread is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# SuperFastPython.com # example of running a function with arguments in another thread from time import sleep from threading import Thread # a custom function that blocks for a moment def task(sleep_time, message): # block for a moment sleep(sleep_time) # display a message print(message) # create a thread thread = Thread(target=task, args=(1.5, 'New message from another thread')) # run the thread thread.start() # wait for the thread to finish print('Waiting for the thread...') thread.join() |
Running the example creates the thread specifying the function name and the arguments to the function.
The thread is started and the function blocks for the parameterized number of seconds and prints the parameterized message.
1 2 |
Waiting for the thread... New message from another thread |
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
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 execute functions in another thread via the “target” argument on the threading.Thread class.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Andrew Pons on Unsplash
Evgenii Kozhanov says
Hello,
Thanks a lot! Your articles are very useful!
Nate Crummett says
Loving this website! I just started reading this afternoon. The present clarity in writing and explanation gives me confidence that I will be able to eventually parallelize nested loops. Thanks a million,
-Nate
Jason Brownlee says
Thank you kindly Nate, I’m happy that the tutorials are helpful.