We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

Multithreading in Python

Multithreading in Python

Multithreading in Python

Multithreading is a process of running multiple tasks at a time in the application. Normally an application will need to work in a fast based on the time. Such a time efficiency is the most important cause of the performance of an application. That kind of time efficiency for the applications will be done by using this Multithreading in all programming languages. In python also use the multithreading concepts.

What is Multitasking?

In general, Multitasking is called as performing multiple tasks simultaneously or parallel. In technical is an Operating System can perform multiple or different tasks at a time. For example, we listen to the songs also downloading and surfing something in a browser simultaneously. All the tasks will be performed by the OS in parallel. This is used to save time and also productivity.

In general, we have two types of multitasking in the OS.

There are

  • Thread based
  • Process-based

In this tutorial, we discuss the thread-based multitasking.

What is Thread?

Thread is a sequential flow of control to run the process. A single process can also have multiple threads. And each thread will do the particular task. For Example, if suppose you are playing a cricket game EA in PC. In that game, the application will consider the single process but it will run the different threads at a time like getting the input from the user, given the sound for commentary, moving the players according to the game playing. All these threads are running synchronously in the single process. And also all these will consider as a thread and perform the particular task in the same application.

In general, all the process has one thread always running it is called the main thread. The main thread is in a stack so that it always running and also creates the sub-threads objects. These sub-threads are initiated by the main thread.

When to use multithreading in python?

Multithreading is a very useful and important process for improving the performance of the application based on the time-saving. But it’s not used in all situations. Because it will be used in dependency between the threads.

In the previous example, EA in that commentary and players moving threads are independent threads. So these are running independently based on the other inputs. So they are not dependent on other threads.

How to achieve multithreading in python?

It achieved in python using module threading. You need to import it.

Before using this module we also install an anaconda environment using the following installation command.

conda install –c conda-forge tbb

After installing the anaconda environment. We need to import the following modules in a program for implement the threading process.

import threading
from threading import *

Creating Threads in python

In python, threads are creating in the following ways.

  • Without creating a class
  • Inheriting the Thread class
  • Without inheriting the Thread class

Without creating class:

In python, we can able to create the thread without creating a class that is possible.

Example:

from threading import *
print(current_thread().getName())
def main_t():
print("Child Thread")
child_t=Thread(target=main_t)
child_t.start()
print("Name of the Executing thread :",current_thread().getName())

Output:

MainThread
Child Thread

Name of the Executing thread: MainThread

In this example, we implement the thread concept without creating the class. Here the first running thread is the main thread. This main thread also creates sub-thread when accessing the method called main_t(). And again the last thread also run by the main thread.

Inheriting Thread class

In this way, the subclass will inherit the superclass called thread class. Also, the subclass can create some sub-threads to perform a task. It also only able to override the methods __init__() and run() to executing the threads. Other life cycle methods are not allowed to override.

Example:

import threading
class my_thread(threading.Thread):
def run(self):
for x in range(5):
print("child thread",x)
a = my_thread()
a.start()

Output:

child thread 0
child thread 1
child thread 2
child thread 3
child thread 4

In this example, we implement the threading using inheriting the thread class. Here we inheriting the Thread class using threading. Thread and also we use the run method of executing the sub-threads. Overrides the run() method and execute it. Because the life cycle of the thread needs to run() method to run the thread After start().

Without inheriting Thread class:

Example:

from threading import *
class ex:
def my_func(self):
for x in range(5):
print("Sub Thread",x)
obj=ex()
t1=Thread(target=obj.my_func)
t1.start()
t1.join()
print("done")

Output:

Sub Thread 0
Sub Thread 1
Sub Thread 2
Sub Thread 3
Sub Thread 4
Done

In this example, we implement creating the thread without inheriting thread class.  Here we create a class with the method called my_func() and run the sub-threads also call the main thread in the last statement.

Advantages of thread:

  • Improved the performance of the application based on the reduced time consumption for response.
  • Reduces the code.
  • The utilization of resources will be better.
  • Allows the tasks to run in parallel as well as concurrent.

In the following examples, we understand the execution of the process based on with and without using multithreading in python.

Example:

import time
def square_func(n):
for i in n:
time.sleep(1)
def cube_func(n):
for i in n:
time.sleep(1)
n=[1,2,3,4,5,6,7,8]
start=time.time()
square_func(n)
cube_func(n)
end=time.time()
print(end-start)

Output:

16.000915050506592

In this example, we are not using any threading concepts for execution. Here this program will take the execution time as 16 secs for a round of.

Now we use the same example with the multithreading concept.

Example:

import threading
from threading import *
import time
def square_func(n):
for i in n:
time.sleep(1)
#print('i%2 = ',i%2)
def cube_func(n):
for x in n:
time.sleep(1)
#print('i%3 = ',i%3)
n=[1,2,3,4,5,6,7,8]
start=time.time()
th1=Thread(target=square,args=(n,))
th2=Thread(target=cube,args=(n,))
th1.start()
time.sleep(1)
th2.start()
th1.join()
th2.join()
end=time.time()
print(end-start)

Output:

9.001514911651611

In this example, we reduce the response time of the previous example as 9 secs round. This is the advantage of implementing multithreading in programs.

Related Blogs:

  1. Brief Overview of Python Language
  2. Python Career opportunities
  3. Python Break Continue
  4. Python Control Flow
  5. Python Data Types
  6. Python Dictionary
  7. Python Exception Handling
  8.  Python File
  9. Python Functions
  10. Python Substring

 

Besant Technologies WhatsApp