How to create a thread using class in Python
In this article, you will learn how to create a thread in Python using classes. But first, let us learn what a thread is. When a process is scheduled for execution, the smallest unit of processing for execution is known as a thread.
In Python, multitasking is achieved by multithreading.
Starting a new thread in Python
thread.start_new_thread ( func, args[, kwargs] )
It works both in windows as well as Linux.
Thread using class
But first, let us understand, what exactly is a class.
- Now, In the code below, we can see how a thread is created using class.
- The class name here is abc.
- Two objects namely obj and obj1 are created inside the class abc.
- Obj.start() initialises the thread.
import threading class abc(threading.Thread) : def run(self) : for _ in range (2) : print(threading.currentThread().getName()) obj= abc(name='Hello') obj1= abc(name='Bye') obj.start() obj1.start()
Output:
Hello Hello Bye Bye
Advantages of Threading in Python
- If a computer system contains multiple CPUs, multiple threads can execute simultaneously. Therefore more programs can execute at the same time, increasing the speed of the process.
- Responsive to input in both the case of single and multiple CPUs.
- Local variables exist in threads.
- A global variable, if changed in one thread causes a change in all other threads as well i.e memory of global variable is shared in threads.
Leave a Reply