Last Updated on September 12, 2022
You can define a new class that extends threading.Thread that automatically starts new threads.
In this tutorial you will discover how to auto-start new threads in Python.
Let’s get started.
Need to Auto-Start a Thread
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.
You can learn more about Python threads in the guide:
A problem with threads is that you must first create an instance of the threading.Thread class, then call the start() function before the thread is started.
In many cases, it would be easier if threads could be started immediately once the class was created.
Is there a way to automatically start threads in Python?
Run loops using all CPUs, download your FREE book to learn how.
How to Auto-Start a Thread
A thread can automatically be started by creating a subclass of threading.Thread that calls the start() function in the constructor.
The typical way a thread is started involves two steps:
- Create the instance of threading.Thread.
- Call the start() function.
For example:
1 2 3 4 5 |
... # create the thread instance thread = threading.Thread(...) # start the thread thread.start() |
This adds an additional step if the goal is to create and start the thread immediately.
In fact, in most cases that a thread is created it is to be started as the next step. Rarely do we need a delay between creating a thread instance and starting the thread.
This can be simplified into a single step that involves:
- Define a custom class that extends threading.Thread.
- Override the class constructor and call start().
Importantly, when extending the threading.Thread class we must call the parent constructor first to ensure that the thread is set up correctly.
We must also pass on all arguments and keyword arguments to the parent constructor so that the new thread is set up correctly, e.g. calls the target task function with any arguments.
You can learn more about extending the threading.Thread class in this tutorial:
The example below defines a custom thread class that automatically starts the thread.
1 2 3 4 5 6 7 8 |
# custom thread class that auto starts the thread class AutoStartThread(Thread):     # constructor     def __init__(self, *args, **kwargs):         # call the the parent constructor         super().__init__(*args, **kwargs)         # start the thread         self.start() |
We can then create an instance of this class that will start the thread immediately.
For example:
1 2 3 |
... # create and start the new thread thread = AutoStartThread(...) |
Next, let’s look at using the automatically starting thread in a worked example.
Example of Auto-Starting a Thread
We can develop an example to demonstrate how to automatically start a new thread.
In this example, we will define a new AutoStartThread class and then use it to execute a custom target function that blocks for a moment and reports a message.
First, we can define the custom class that extends the threading.Thread class, passes along all arguments to the parent constructor, then starts the thread.
We will use the AutoStartThread class defined in the previous section, provided again below.
1 2 3 4 5 6 7 8 |
# custom thread class that automatically starts threads when they are constructed class AutoStartThread(Thread):     # constructor     def __init__(self, *args, **kwargs):         # call the the parent constructor         super().__init__(*args, **kwargs)         # start the thread         self.start() |
Next, we can define a custom task function to execute in a new thread.
The function will first print a message to let us know that the thread is running, it will then sleep for one second by calling time.sleep(), then reports a final message before the thread terminates.
The task() function below implements this.
1 2 3 4 5 6 7 |
# task function def task():     print('Task starting')     # block for a moment     sleep(1)     # report     print('Task all done') |
Finally, the main thread will create an instance of the AutoStartThread class configured to execute our task() function.
Creating a new instance will start the new thread immediately.
1 2 3 |
... # create and start the new thread thread = AutoStartThread(target=task) |
You can learn more about executing functions in a new thread in this tutorial:
The main thread will then block until the new thread terminates. This can be achieved by calling the join() function.
You can learn more about joining threads in this tutorial:
1 2 3 |
... # wait for the new thread to finish thread.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 26 |
# SuperFastPython.com # example of automatically starting a thread from time import sleep from threading import Thread  # custom thread class that automatically starts threads when they are constructed class AutoStartThread(Thread):     # constructor     def __init__(self, *args, **kwargs):         # call the the parent constructor         super().__init__(*args, **kwargs)         # start the thread         self.start()  # task function def task():     print('Task starting')     # block for a moment     sleep(1)     # report     print('Task all done')  # create and start the new thread thread = AutoStartThread(target=task) # wait for the new thread to finish thread.join() |
Running the example first creates an instance of the new thread class.
The constructor of the new thread class calls the parent constructor of the threading.Thread class, which ensures that the new thread is set up correctly. The constructor then starts the new thread immediately.
The main thread then joins the new thread and waits for it to terminate.
The new thread executes our custom task function. A message is printed, the thread sleeps for a moment, then a final message is reported before the thread terminates.
1 2 |
Task starting Task all done |
This demonstrates how to define a new class for auto-starting new threads, and how it can be used to execute task functions.
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
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
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
Takeaways
You now know how to auto-start new threads in Python
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Loïc Lassence on Unsplash
Do you have any questions?