Multi-threading in Python - Why & Where to Use

It displays four threads owned by a single process which is called multi-threading. It is a tutorial of multi-threading in python.

Introduction

In today's digital world, the role of various software in human life is outstanding. An important software can reduce human headaches by performing a specific task most efficiently in less time. Programming is the most important part of any kind of software development and the higher the performance of software, the higher the level of programming behind it.

In this type of application development, one must not only know programming but also have a fundamental knowledge of how computer systems work actually. There are so many things that come under Operating System. For example, Memory Management, File System, I/O system, Process Management, and many more but in this tutorial, we will discuss a very common but crucial topic which is Multi-threading.

Since this is a Python Tutorial, we will cover this topic with python programming examples, so the title of this topic would be Multi Threading in Python and now it sounds better. But before we get to the core, you must have a roughly knowledge of Process and Threads.

👉Visit AlsoMeditation App in Python Tkinter: Practice Deep Breathing

What are a Process and Threads?

If you have done C programming, you may have seen after compiling the dot(.) c file, the compiler generates a ./a.out file which is called an executable file too. So you may call the .c file as the source code and ./a.out is the executable code. When you run this ./a.out file, a process is created. So you can say a program in execution is called a Process.

There is another unit of execution which is called Threads. In simpler, a process can have many units of execution which is known by threads. So a process can be multi-threaded

Let me give you an example. When you open your Chrome Browser, the OS creates a separate process for it but if you open multiple tabs there for performing multi-tasking(for example, one tab is for YouTube video playing, one is for downloading a file from the internet, and so on.) each of those tabs will be referred as a thread.

So, in summarize, if you open multiple applications(for example, Chrome browser, MS Office, PhotoShop, etc.) those will be treated as a separate process for each application which will be called multiprocessing together in execution, but inside each process, there may have multiple threads for multiple functionalities and this time it would be multi-threading.

I hope now the basic idea of Process and Threads are pretty much clear to you. You might be thinking about why we need multiprocessing and multi-threading in our python programming though we are not building an app like MS Office or Chrome. OK, you will get your answer shortly in a few minutes. Just keep reading until the end.

Solving a Problem without Multi Threading

Why do we use multi-threading in our python program? Let me describe it with a programming example

Here, I will create a Tkinter window to display a countdown time of 5 seconds on that. The program will perform the countdown operation as well as the displaying operation on a Tkinter widget(Label).

The challenging task here is to see how the program could manage those two tasks under a single process. I'm assuming that you have roughly knowledge about the GUI programming with the Tkinter library(If interested, visit the separate page to get more than 20+ free GUI projects). If not, don't worry, the code will be too simple to understand. I've added a single comment line before each line of the code. Let's get straight to the main program.

Code


import time
from tkinter import *
from threading import *

# Declaring variables for global use
TimeLabel = None
# Setting the countdown time (5 seconds in this case)
c_time = 5

# Function to create a GUI window
def Window(root):
global TimeLabel

window = root
window.geometry("480x320")
window.title("Demo App")
window.resizable(height = False, width=False)

# A Label widget for showing the remaining time
TimeLabel = Label(window, text="0:0", bg="black", \
fg="white", font=("Courier", 22))
TimeLabel.place(x=205, y=120)

CountDown()

def CountDown():
global TimeLabel
global c_time

while c_time > 0:
# Print the remaining time
print(c_time)
# Display the remaining time
TimeLabel.config(text=f"{0}:{c_time}")
# sleep for 1 second
time.sleep(1)
# reduce c_time by 1
c_time -= 1

# Main function
if __name__ == "__main__":
root = Tk()
Window(root)
root.mainloop()

Output

As you can see, first, the program prints the remaining time on the terminal and then displays the GUI window but this was not supposed to happen. I wanted to print and display at the same time parallelly but it happened something else.

Here, comes the usage of multi-threading. Python offers a module called threading which allows us to create a different thread within the process where the main program is running.

Solving the same problem but using Multi Threading

Here we will create a separate thread to handle only the countdown function so that the main program can perform other tasks perfectly. I will use the python threading module to create a different thread under the process where the main program is running(See the image below to understand it better). Let's see what happens this time.

This demonstrates the multi-threading approach where two functions of a python program belong to the same process.
Image - Multi-threading

Code


import time
from tkinter import *
from threading import *

# Declaring variables for global use
TimeLabel = None
# Setting the countdown time (5 seconds in this case)
c_time = 5

# Function to create a GUI window
def Window(root):
global TimeLabel

window = root
window.geometry("480x320")
window.title("Demo App")
window.resizable(height = False, width=False)

# A Label widget for showing the remaining time
TimeLabel = Label(window, text="0:0", bg="black", \
fg="white", font=("Courier", 22))
TimeLabel.place(x=205, y=120)

MultiThreading()

def MultiThreading():
x = Thread(target=CountDown)
x.start()

def CountDown():
global TimeLabel
global c_time

while c_time > 0:
# Print the remaining time
print(c_time)
# Display the remaining time
TimeLabel.config(text=f"{0}:{c_time}")
# sleep for 1 second
time.sleep(1)
# reduce c_time by 1
c_time -= 1

# Main function
if __name__ == "__main__":
root = Tk()
Window(root)
root.mainloop()

Output

Why we didn't use multiprocessing here?

You might be wondering why I didn't use multiprocessing there even though multiprocessing is also used for parallel programming. The major reason is so simple but I will tell you that through an example so that you can grab the point better.

Python offers a module called multiprocessing and I will use it to solve the same problem that I solved just before but using multi-threading. Let's see what happens this time.

Code


import time
from tkinter import *
import multiprocessing as mp

# Declaring variables for global use
TimeLabel = None
# Setting the countdown time (5 seconds in this case)
c_time = 5

# Function to create a GUI window
def Window(root):
global TimeLabel

window = root
window.geometry("480x320")
window.title("Demo App")
window.resizable(height = False, width=False)

# A Label widget for showing the remaining time
TimeLabel = Label(window, text="0:0", bg="black", \
fg="white", font=("Courier", 22))
TimeLabel.place(x=205, y=120)

MultiProcessing()

def MultiProcessing():
# Creating a process
x = mp.Process(target=CountDown)
x.start()

def CountDown():
global TimeLabel
global c_time

while c_time > 0:
# Print the remaining time
print(c_time)
# Display the remaining time
TimeLabel.config(text=f"{0}:{c_time}")
# sleep for 1 second
time.sleep(1)
# reduce c_time by 1
c_time -= 1

# Main function
if __name__ == "__main__":
root = Tk()
Window(root)
root.mainloop()

Output

As you can see the program prints the remaining time in the terminal but couldn't display that time on the Label widget of the Tkinter window. Let me tell you why this discrimination happened.

The window was created under one process but here we created a different process to manage the countdown function(See the image below to understand it better).

This demonstrates the multiprocessing approach where two functions of a python program belong to two different process.
Image - MultiProcessing

Under the second process, we tried to print(on the console/terminal) and display the remaining time on the Tkinter window. Since every process owns a separate address space and the Tkinter window belongs to another process, that is why the newly created process couldn't update that.

Actually, processes do not share memory and resources with each other and that is why the newly created process could not access data and code from the process under which the code for the GUI window was running.

But since a process can have multiple threads, they all share the same memory space and resources. For this reason, we did not use multiprocessing to solve the above problem.

I hope the logic is clear to you now.

👉Visit Also: Image to Pencil Sketch Converter in Python

Summary

In this tutorial, we have covered What are a Process and Threads, and why and when to apply those two beautiful methods in our programming. As an example, we took a beautiful programming example where the task was to print(on console/terminal) and display countdown time on the Tkinter window.

We created two programs to solve this problem using and not using multi-threading methods respectively. In closing, we tried to solve the same problem using multiprocessing but found something discrimination in this case.

I hope the topic we discussed here, "Multi Threading in Python" is pretty much clear to you now. For any query or doubt related to this topic, just leave your message below. You will get an immediate response.

Have a nice day ahead, cheers!

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post