In this post, we will discuss how to create threads in Python.
You can use the ‘Thread‘ class from Python’s threading module to create threads. You must create an object of the Thread class if you want to create your own thread. We can make the threads in Python in the ways mentioned below.
- Creating a thread by not relying on a class
- Creating a thread by adding a sub-class to the Thread class
- Creating a thread without adding a subclass to the Thread class
We will explore each way of creating threads in Python with examples.
Link to all chapters of our Python Tutorial series: Learn Python
Make Threads by not relying on a Class
The objective of threads is to execute a set of statements such as a function. It means that we can make threads by creating an object of the Thread class and passing the function’s name as a target for the thread, as mentioned below.
t=Thread(target=nameOfFunction, [args = (arg1,arg2,..)]
In the format above, we have ‘t‘, an object we created for the Thread class. The ‘target‘ refers to the function on which the thread should act. The ‘args‘ represents arguments in a tuple. After a thread is created, as shown in the format above, we should start it by calling the start() method as shown below.
t.start()
Let us look at a program to create a thread by not relying on a class.
#Python program to create a thread by not relying on a class
#importing the threading module
from threading import *
#create a function
def displayOutput():
print("This is output getting printed!")
#create a thread to run the function 3 times
for num in range(3):
#create thread and mention the target function
t = Thread(target=displayOutput)
#start the thread
t.start()
Output:
This is output getting printed!
This is output getting printed!
This is output getting printed!
In the above program, we imported the threading module and created a function called ‘displayOutput‘. After this, we made a loop to run the thread three times. The thread that we’ve created targets the ‘displayOutput‘ function, and this function runs three times due to the loop we’ve created.
Make Thread by adding a Sub Class to the Thread Class
We know that the Thread class is available already in the threading module. You can create a sub-class in your program that inherits the Thread class’s characteristics from the threading module, as shown below.
class SampleSubClass(Thread):
In the format shared above, ‘SampleSubClass‘ is the subclass that inherits the Thread class’s characteristics. It means that all Thread class methods become available to the ‘SampleSubClass‘ through inheritance. All the methods, such as the run() method available in the ‘Thread‘ class, become available to the ‘SampleSubClass‘, and you will have to override the run() method to add your code. Since this run() method runs every time a thread is started in normal scenarios, we need to override this method with our code.
After creating the thread and starting it using the start() method, you will have to also use the join() method to wait till the thread finishes the execution. Let us look at an example program now.
#Creating thread by inheriting the Thread class
#import the threading module
from threading import *
#create a new class and add it as sub class for the Thread class
#through inheritance
class SampleSubClass(Thread):
#override the run method from the thread class
def run(self):
for num in range(1,4):
print(num)
#create instance for the SampleSubClass class
t1 = SampleSubClass()
#commence the running of thread t1
t1.start()
#wait until the thread finishes execution
t1.join()
Output:
1
2
3
In the above program, we created a new class, ‘SampleSubClass‘ and added it as a sub-class of the ‘Thread‘ class from the threading module through inheritance. Within the ‘SampleSubClass‘, we added a run() method with our code that overrides the run() method of the Thread class. Eventually, after starting the thread with the start() method, we also used the join() method to wait till the thread’s completion.
Make Thread without adding a subclass to the Thread class
It is also possible to make a thread using an individual class that does not inherit the functionalities of the ‘Thread’ class. To accomplish the same, we have to create an object for this class and pass the object.method() as the target method for the thread. Let us find out how in the below example program.
#Creating a thread without creating a sub class for the Thread class
#import the threading module
from threading import *
#create an individual class
class SampleClass:
#add constructor
def __init__(self,word):
self.word = word
#define a method
def displayOutput(self,a,b):
print(self.word)
print("The arguments are: {} and {}".format(a,b))
#create an object for SampleClass and pass a string
obj1 = SampleClass("Namaskaaram")
#create a thread to run the displayOutput method of the obj1
t1 = Thread(target=obj1.displayOutput,args=(1,2))
#run the thread
t1.start()
Output:
Namaskaaram
The arguments are: 1 and 2
In the above program, we imported the threading module, created a class with a constructor to accept a string, and a method to display the string and the arguments. We then created an object, ‘obj1‘ and passed ‘obj1.displayOutput‘ as the target method for the thread in this program. Eventually, we started the thread using the start() method.
Thread Class Methods
We saw methods like the start() method that commences the thread’s execution. Similarly, there are other thread class methods that you can use in your program to implement threading much more smoothly in your programs.
Property or Method | Description |
t.daemon | This property accepts either True or False to establish the thread as a Daemon or not |
t.isDaemon() | Returns True if a thread is a Daemon, or else it returns False |
t.setDaemon(flag) | Sets a thread as Daemon thread if the flag is True |
t.name | This property refers to the name of the thread |
t.getName() | Returns the name of the thread |
t.setName(name) | Assigns a name to the thread |
t.is_alive() | Returns True if the thread is active in the memory. In other cases, it returns False. A thread is considered active after its start() method is called and until its run() method ends. |
t.join([timeout]) | Waits until the thread ends or a timeout happens. |
t.start() | Commences the thread |