Multithreading in Python

Multithreading in Python with Examples

In this article, I am going to discuss Multithreading in Python with examples. Please read our previous article where we discussed Logging in Python. As part of this article, we are going to discuss the following pointers in detail.

  1. What is Multitasking?
  2. Process based and Thread based Multitasking
  3. Applications of Multithreading
  4. How to implement Multithreading in Python?
  5. Different Ways to Create a Thread in Python
  6. Creating a Thread using Thread class
  7. Creating a Thread class by inheriting Thread class
  8. Advantages of multithreading in Python
  9. Naming a Thread in Python
  10. Thread Identification Number (ident)
What is Multitasking?

The process of executing many tasks simultaneously is called the concept of multitasking. The multitasking can be done in two ways:

  1. Process based Multitasking
  2. Thread based Multitasking
Process based Multitasking:

Executing several tasks simultaneously where each task is a separate independent process is called Process based multitasking. For example,

  1. Typing the program
  2. Download the file

These tasks are executing simultaneously and independently of each other. It is process based multitasking. This type of multi-tasking is best suitable at operating system level.

Thread based Multitasking:

Executing several tasks simultaneously where each task is a separate independent part of the same program, is called Thread based multitasking. Here, each independent part is called a thread. This type of multi-tasking is best suitable at programmatic level.

Note: Whether it is process based or thread based, the main advantage of multi-tasking is to improve performance of the system by reducing response time.

In this article, we are going to discuss in detail about multithreading, the thread based multitasking, and its implementation in python.

Area of Multithreading:

The main important application areas of multithreading are:

  1. To implement Multimedia graphics
  2. To develop animations
  3. To develop video games
  4. To develop web and application servers etc.
How to implement Multithreading in Python?

Where-ever a group of independent jobs are available, then it is highly recommended to execute them simultaneously instead of executing one by one using the concept of multithreading.

Python provides one inbuilt module named “threading” to provide support for implementing multithreading concepts.

So, developing multi-threaded Programs is very easy in python. The key point to remember is that, every Python Program by default contains one thread which is nothing but MainThread.

Program: Introduction to Multithreading (demo1.py)

import threading
print("Current Executing Thread:",threading.current_thread().getName())

Output: Multithreading in Python with Examples

The threading module contains function current_thread() which returns the current executing Thread object. We need to call getName() method by using thread object to know the current executing thread name.

Different Ways to Create a Thread in Python

There are two ways in which we can create a thread in python. They are as follows:

  1. Creating a Thread with pre-defined ‘Thread’ class
  2. Creating a our own thread class by inheriting Thread class
Creating a Thread using Thread class:

There is a pre-defined class named ‘Thread’ available within the ‘threading’ module. We can create threads by using that inbuilt class.

Program: Creating a Thread with pre-defined ‘Thread’ class in python (demo2.py)

from threading import *
def display():
   for i in range(6):
       print("Child Thread")
t=Thread(target=display)
t.start()
for i in range(6):
   print("Main Thread")

Output:

Creating a Thread with pre-defined ‘Thread’ class in python

We created an object ‘t’ for the class ‘Thread’ with the target as display() method. Whenever we call start() method using the object ‘t’, the thread execution starts. The display() method will be executed parallely along with the other parts of the program.

If multiple threads are present in our program, then we cannot expect exact execution order in output. Because of this we cannot provide exact output order for the above program. It varies from machine to machine while running.

Program: Creating a Thread with pre-defined ‘Thread’ class in python (demo3.py)
from threading import *
class Demo:
   def display(self):
       for i in range(6):
           print("Child Thread")
obj=Demo()
t=Thread(target=obj.display)
t.start()
for i in range(6):
   print("Main Thread")

Output:

Creating a Thread with pre-defined ‘Thread’ class in python

The demo3.py, is the similar program to demo2.py. The main intention is to show how threading can be implemented to methods and classes.

Creating a Thread class by inheriting Thread class:

We can create a thread by predefined Thread class. Here our class should inherit Thread predefined class in python. Predefined Thread class contains run() method. In our child class we need to override the run() method with our required functionality. Whenever we call start() method then automatically run() method will be executed and performs our job.

Program: Creating a Thread class by inheriting Thread class in python (demo4.py)

from threading import *

class MyThread(Thread):
   def run(self):
       for i in range(6):
           print("Child Thread")
t=MyThread()
t.start()
for i in range(6):
   print("Main Thread")

Output:

Creating a Thread class by inheriting Thread class in python

Advantage of multithreading:

As told, the main advantage of multi-tasking is to improve performance of the system by reducing response time. Let’s see it in the example below

Program: Multithreading in python (demo5.py)

from threading import *
import time
def divison(numbers):
   for n in numbers:
       time.sleep(1)
       print("Double:", n/5)

def multiplication(numbers):
   for n in numbers:
       time.sleep(1)
       print("Square:", n*5)
numbers=[10,20,30,40,50]
begintime=time.time()
divison(numbers)
multiplication(numbers)
print("The total time taken:", time.time()-begintime)

Output:

Multithreading in python

Program: multithreading in python (demo6.py)
from threading import *
import time
def divison(numbers):
   for n in numbers:
       time.sleep(1)
       print("Double:", n/5)

def multiplication(numbers):
   for n in numbers:
       time.sleep(1)
       print("Square:", n*5)

numbers=[10,20,30,40,50]
begintime=time.time()
t1=Thread(target=divison,args=(numbers,))
t2=Thread(target=multiplication, args=(numbers,))
t1.start()
t2.start()
t1.join()
t2.join()

print("The total time taken:", time.time()-begintime)

Output:

multithreading Examples in python

In the above two programs, the execution time of the demo6.py (with multithreading) is nearly half the time of demo5.py (without multithreading). In real time, this would bring a great advantage in terms of execution time.

Note: In order to show some notable time, in the program we have used the sleep(n) method which delays or stops the program execution for n seconds. ‘time’ is an in-built python module and time.time() will give us the current time and time.sleep() will delay the execution.

Naming a Thread in Python:

Every thread in python has some name associated with it. It might be the default name generated by Python or a name which can also be customized.

object.setName(<name>) : To set our own name
object.getName() – Returns Name of Thread

Program: set and get the name of a thread in python (demo7.py)

from threading import *
print("Main thread name",current_thread().getName())
current_thread().setName("MyThread")

print("After customise the thread name: ",current_thread().getName())

Output:

Naming a Thread in Python

As already stated, current_thread() will return an object to the current thread. By the default the program runs on Main Thread.

Thread Identification Number (ident):

For every thread internally, a unique identification number will be available. We can access this by using implicit variable “ident”.

Program: Thread Identification Number in python (demo8.py)

from threading import *
def m():
   print("Child Thread")
t=Thread(target=m)
t.start()
print("Main Thread Identification Number:", current_thread().ident)
print("Child Thread Identification Number:", t.ident)

Output:

Thread Identification Number in python

In the next article, I am going to discuss Important Methods of Thread class in Python. Here, in this article, I try to explain Multithreading in Python with Examples. I hope you enjoy this Multithreading in Python with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.