/    /  Python Multi-threading

Python multi-threading

A Set of Statements Created in a Python Program are executed through Python Virtual Machine (PVM) which converts the Python Code into Byte Code, Python Interpreter acts as Python Virtual Machine. The Process of executing the Statements through Python Virtual Machine is called Thread. Hence mentioned above any Program internally has a thread running as a part of Python Virtual Machine (PVM) while execution.

Thread functions are hosted in Threading Library.


Python Example:

Let us understand the process through a simple example below:


import threading 
print("What is the Current Thread?")
print("Currently Running Thread is: ",threading.current_thread().getName())
if threading.current_thread() == threading.main_thread():
	print("Current Thread is the main Thread")
else:
	print("Current Thread is not main Thread")


Tasking:

As mentioned above, thread represents the execution of statements. Statement Execution comprises of two types:

  • Single Tasking
  • Multi-Tasking

Precisely, Task can be defined as process of doing some calculation, processing logic, Assignment etc.,

In Single Tasking, processor accepts one task at a time which implies that if there are multiple logics present in the program, till one task completes rest of the tasks should wait to execute as in single Tasking, only one task is given to microprocessor at a time.


On the Other hand, in Multi-Tasking, we can have a processor handling multiple jobs at a time that means processor performing multiple tasks at a time. We have two types of Multi-Tasking:

  • Process-Based Multi-Tasking
  • Thread Based Multi-Tasking

In Process-Based Multi-Tasking, Micro Processor executes several programs at a time.

In Thread Based Multi-Tasking, multiple tasks within the same program are executed simultaneously.

Till now we have mentioned in detail about Thread, its Capability to perform across Single Tasking and Multi-Tasking and types of Multi-Tasking as well.


Let us discuss in few lines about Multi-Threading. As the name suggests, Multi-Threading is the ability of executing multiple threads concurrently by the Processor.

This can be demonstrated in a programmatical manner through Queues.

from threading import *
from time import *
from queue import *
#Create Parent Class
class Parent:
	def __init__(self):
		self.q = Queue()
	def par(self):
		for i in range (1,6):
			print(‘Parent item: ‘, i)
			self.q.put(i)
			sleep(2)
#Create Child Class
Class Child:
	def __init__(self, var):
		self.var = var
	def ch(self):
		for i in range(1,6):
			print(‘Child item: ‘,self.var.q.get(i))
p = parent() #Create Parent Object
c = child(p) # Create Child Object and pass Parent Object as parameter
# Create Parent and Child Threads
t1 = Thread(target=p.par)
t2 = Thread(target=c.ch)
#Now run the threads
t1.start()
t2.start()