Threading in Python
Thread is the smallest individual program which contains some instruction,Basically thread is worked under the process.
Goal of thread is a “parallelism”
To divide the process into multiple threads.
Let’s understand by Example:
If you have application MS office and I used Microsoft Word, In this we are writing something,we change the font ,colour and use format painter so Microsoft office provides so many features. So we can break down one process into a small process .Each small process is called the Thread.
Program
class A: def a(self): print("A") class B: def b(self): print("B") obj=A() obj1=B() for x in range(5): obj.a() obj1.b()
Output
A B A B A B A B A B
In this output you observe that first print obj and second time print obj1 due to processor attention,
Motive of threading is to break one process into a small thread and run it simultaneously.
Let’s rectify this.
from time import sleep #delay function import from threading import * #thread import class A(Thread): def run(self): #inbuilt function of thread for x in range(5): print("A") sleep(1) class B(Thread): def run(self): for x in range(5): print("B") sleep(1) obj=A() obj1=B() obj.start()# initialize the thread obj1.start()
Output
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> === RESTART: C:/Users/laptop/AppData/Local/Programs/Python/Python38-32/thread.py === >>> AB AB BA BA A B
Here you can see output is the same time given by the interpreter