Skip to content
Related Articles

Related Articles

Improve Article

Implementing Threading without inheriting the Thread Class in Python

  • Last Updated : 05 Sep, 2020

We are going implement threading in Python using a Class without sub-classing the superclass called Thread.

To make the best use of the underlying processor and to improve the performance of our application, we can create multiple threads that can execute in parallel. Making the best use of the processor and also our application will give the best user experience, it will be fast.

There are three ways to create threads in Python:

  1. Using a function
  2. Extending thread class
  3. Without extending thread class

We will implement the last approach is also called the hybrid approach. We will define a Class but the Class will not extend the parent class thread instead we are going to directly define any function inside that we want. Instead, we will create an instance of the thread and then pass the object and the function which we want to execute within that object as the target and the argument is the second argument. Then invoke the Thread start method.

Example 1:
Implementing Thread by printing the first 10 natural numbers
 



Python3




# importing thread module
from threading import *
  
# class does not extend thread class
class MyThread:
    def display(self):
        i = 0
        print(current_thread().getName())
        while(i <= 10):
            print(i)
            i = i + 1
  
# creating object of out class
obj = MyThread()
  
# creating thread object
t = Thread(target = obj.display)
  
# invoking thread
t.start()

Output:

Thread-1
0
1
2
3
4
5
6
7
8
9
10

Example 2:
Implementing Thread by printing even numbers within a given range

Python3




# importing thread module
from threading import *
  
# class does not extend thread class
class MyThread:
    def display(self):
        i = 10 
        j = 20
        print(current_thread().getName())
        for num in range(i, j + 1):
            if(num % 2 == 0):
                print(num)
  
# creating an object of our class                
obj = MyThread()
  
# creating a thread object
t = Thread(target = obj.display)
  
# invoking the thread
t.start()

 Output:

Thread-1 
10 
12 
14 
16 
18 
20

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :