Multithreading in Python and How to Achieve it?

Aayushi Johari
Edureka
Published in
6 min readMay 17, 2019
Multithreading in Python — Edureka

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.

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

  1. What is multitasking in Python?
  2. What is a thread?
  3. When to use multithreading in Python?
  4. How to achieve Multithreading in Python?
  5. How to create threads in Python?
  • without creating a class
  • by extending thread class
  • without extending thread class

6. 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:

  • Process-based
  • Thread-based

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.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Python Tutorial

2. Python Programming Language

3. Python Functions

4. File Handling in Python

5. Python Numpy Tutorial

6. Scikit Learn Machine Learning

7. Python Pandas Tutorial

8. Matplotlib Tutorial

9. Tkinter Tutorial

10. Requests Tutorial

11. PyGame Tutorial

12. OpenCV Tutorial

13. Web Scraping With Python

14. PyCharm Tutorial

15. Machine Learning Tutorial

16. Linear Regression Algorithm from scratch in Python

17. Python for Data Science

18. Loops in Python

19. Python RegEx

20. Python Projects

21. Machine Learning Projects

22. Arrays in Python

23. Sets in Python

24. Python Interview Questions

25. Java vs Python

26. How To Become A Python Developer?

27. Python Lambda Functions

28. How Netflix uses Python?

29. What is Socket Programming in Python

30. Python Database Connection

31. Golang vs Python

32. Python Seaborn Tutorial

33. Python Career Opportunities

Originally published at https://www.edureka.co on May 17, 2019.

--

--

Aayushi Johari
Edureka

A technology enthusiast who likes writing about different technologies including Python, Data Science, Java, etc. and spreading knowledge.