Auto-Start Threads in Python
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?
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:
...
# 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.
# 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:
...
# 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.
# 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.
# 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.
...
# 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:
...
# wait for the new thread to finish
thread.join()
Tying this together, the complete example is listed below.
# 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.
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.
Takeaways
You now know how to auto-start new threads in Python