What is Mutithreading in Python and How to Achieve it?

Last updated on Nov 26,2019 13K Views

What is Mutithreading in Python and How to Achieve it?

edureka.co

Time is the most critical factor in life. Owing to its importance, the world of programming provides various tricks and techniques that significantly help you reduce the time consumption, thereby increasing performance. One such approach is Multithreading in Python, which is one of the most important concepts covered under Python Certification Training.

Here is a quick summary of all the majors covered in this article:

What is multitasking in Python?
What is a thread?
What is multithreading in python?
When to use multithreading in Python?
How to achieve Multithreading in Python?
How to create threads in Python? 

Advantages of using multithreading in Python

To begin with, let us first try to understand multitasking before we start learning about Multithreading in Python.

What is Multitasking in Python?

Multitasking, in general, is the capability of performing multiple tasks simultaneously. In technical terms, multitasking refers to the ability of an operating system to perform different tasks at the same time. For instance, you are downloading something on your PC as well as listening to songs and concurrently playing a game, etc. All these tasks are performed by the same OS an in sync. This is nothing but multitasking which not just helps you save time but also increases productivity.

There are two types of multitasking in an OS:

In this article, you will be learning about Thread-based multitasking or Multithreading.

What is a thread?

A thread is basically an independent flow of execution. A single process can consist of multiple threads. Each thread in a program performs a particular task. For Example, when you are playing a game say FIFA on your PC, the game as a whole is a single process, but it consists of several threads responsible for playing the music, taking input from the user, running the opponent synchronously, etc. All these are separate threads responsible for carrying out these different tasks in the same program.

Every process has one thread that is always running. This is the main thread. This main thread actually creates the child thread objects. The child thread is also initiated by the main thread. I will show you all further in this article how to check the current running thread.

So with this, I hope you have clearly understood what is a thread. Moving on, let’s see what is Multithreading in Python.

When to use Multithreading in Python?

Multithreading is very useful for saving time and improving performance, but it cannot be applied everywhere.
In the previous FIFA example, the music thread is independent of the thread that takes your input and the thread that takes your input is independent of the thread that runs your opponent. These threads run independently because they are not inter-dependent.

Therefore, multithreading can be used only when the dependency between individual threads does not exist.

This article further shows how you can achieve Multithreading in Python.

How to achieve Multithreading in Python?

Multithreading in Python can be achieved by importing the threading module.

Before importing this module, you will have to install this it. To install this on your anaconda environment, execute the following command on your anaconda prompt:

conda install -c conda-forge tbb

After its successfully installed, you can use any of the following commands to import the threading module:

import threading
from threading import *

Now that you have threading module installed, let us move ahead and do Multithreading in Python.

How to create threads in Python?


Threads in Python can be created in three ways:

  1. Without creating a class
  2. By extending Thread class
  3. Without extending Thread class

Without creating a class

Multithreading in Python can be accomplished without creating a class as well. Here is an example to demonstrate the same:

Example:

from threading import *
print(current_thread().getName())
def mt():
    print("Child Thread")
child=Thread(target=mt)
child.start()
print("Executing thread name :",current_thread().getName())

Output:

MainThread
Child Thread
Executing thread name : MainThread

The above output shows that the first thread that is present is, the main thread. This main thread then creates a child thread that is executing the function and then the final print statement is executed again by the main thread.

Now let us move ahead and see how to do Multithreading in python by extending the Thread class.

By extending the Thread class:

When a child class is created by extending the Thread class, the child class represents that a new thread is executing some task. When extending the Thread class, the child class can override only two methods i.e. the __init__() method and the run() method. No other method can be overridden other than these two methods.

Here is an example of how to extend the Thread class to create a thread:

Example:

import threading
import time
class mythread(threading.Thread):
    def run(self):
        for x in range(7):
        print("Hi from child")
a = mythread()
a.start()
a.join()
print("Bye from",current_thread().getName())

Output:
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Bye from MainThread

The above example shows that class myclass is inheriting the Thread class and the child class i.e myclass is overriding the run method. By default, the first parameter of any class function needs to be self which is the pointer to the current object. The output shows that the child thread executes the run() method and the main thread waits for the childs execution to complete. This is because of the join() function, which makes the main thread wait for the child to finish.

This method of creating threads is the most preferred method because its the standard method. But in case you want to create threads without inheriting or extending the Thread class, you can do it in the following manner.

Without Extending Thread class

To create a thread without extending the Thread class, you can do as follows:
Example:

from threading import *
class ex:
def myfunc(self): #self necessary as first parameter in a class func
    for x in range(7):
        print("Child")
myobj=ex()
thread1=Thread(target=myobj.myfunc)
thread1.start()
thread1.join()
print("done")

Output:

Child
Child
Child
Child
Child
Child
Child
done

The child thread executes myfunc after which the main thread executes the last print statement.

Advantages of using threading

Multithreading has many advantages some of which are as follows:

  • Better utilization of resources
  • Simplifies the code
  • Allows concurrent and parallel occurrence of various tasks
  • Reduces the time consumption or response time, thereby, increasing the performance.

Here is an example to check how long it takes for a code to execute with and without multithreading in python:

Example:
import time
def sqr(n):
    for x in n:
        time.sleep(1)
        x%2
def cube(n):
    for x in n:
        time.sleep(1)
        x%3
n=[1,2,3,4,5,6,7,8]
s=time.time()
sqr(n)
cube(n)
e=time.time()
print(e-s)

Output:

16.042309284210205

The above is the output time taken to execute the program without using threads. Now let us use threads and see what happens to the same program:

Example:

import threading
from threading import *
import time
def sqr(n):
    for x in n:
        time.sleep(1)
        print('Remainder after dividing by 2',x%2)
def cube(n):
    for x in n:
        time.sleep(1)
        print('Remainder after dividing by 3',x%3)
n=[1,2,3,4,5,6,7,8]
start=time.time()
t1=Thread(target=sqr,args=(n,))
t2=Thread(target=cube,args=(n,))
t1.start()
time.sleep(1)
t2.start()
t1.join()
t2.join()
end=time.time()
print(end-start)
Output: 9.040220737457275

The above output clearly shows that the time taken when we use threads is much less compared to the time taken for the same program to execute without using threads.

I hope you are clear with the concepts covered under this article related to Multithreading in Python. Make sure to practice as much as possible as this is one of the most important concepts used in programming. 

Got a question for us? Please mention it in the comments section of this “Multithreading in Python” blog and we will get back to you as soon as possible.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access. 

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 30th November,2024

30th November

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Time Series Analysis using Python