Speed Boost: How Multi-Threading Makes Your Programs Faster

Tushar
4 min readNov 27, 2023

Imagine you’re at a grocery store, and you need to buy a bunch of items. Now, you have two options:

Option 1: You’re the only person shopping, and you have to go through each aisle one by one, picking up items and waiting in line at the checkout each time. It’s like a slow-motion shopping marathon, and you end up spending a lot of time.

Option 2: You bring a friend (or a few friends) with you. Each person takes a separate aisle, grabs items simultaneously, and you all meet up at the checkout. It’s like a synchronized shopping dance, and you finish much faster!

Now, replace “you” with a computer program, “aisles” with tasks, and “friends” with threads. That’s essentially multi-threading! In the computer world, programs have different tasks to perform, and multi-threading allows them to tackle those tasks simultaneously, making the whole process faster and more efficient.

In super easy language, what exactly is a thread?

Think of a thread as a helper inside your computer that can do one thing at a time. If your computer is like a kitchen, a thread is like a little chef handling one task, and when you have many chefs (threads), the kitchen gets things done quicker!

The thread has to go through various stages of its life.

Life-Cycle of a Thread

Getting Ready (New)

The thread is created but hasn’t started yet.

Time to Work (Runnable/Ready)

Now the Task is assigned , the thread is all set to start the job.

Working Hard (Running/Active)

The thread is actively doing its task, just like a worker doing their job.

Taking a Break (Waiting/Blocked)

Sometimes, the thread needs to wait a bit, like taking a short break until things are ready.

Job Done (Dead/Terminiated)

Finally, the thread finishes its job and is done for the day, just like a worker going home after work.

How things can be implemented using Python.

Python makes things easier with the a built in module threading which takes care of everything.

from threading import Thread

The thread class is all you need for creating and using multiple threads in your Python program

There are various ways by which we can create threads

Firstly let's create a thread by Thread class object

from threading import Thread, current_thread
from time import sleep

def task(f_name:str, l_name:str) -> None:
"""
This is a simple function which greets the provided name
:param:
f_name -> a string of any length
l_name -> a string of any length
:return:
None -> Simply nothing
"""

executing_thread = current_thread() # return the current thread object

print(f"Execution of task is started by {executing_thread.name}")

sleep(5) # puts the thread in waiting/blocked state for 5 secs.

print(f"Hello {f_name} {l_name} by {executing_thread.name}")



thread = Thread(
name = "CustomThread", # optional param if not provided name will be Thread-x
target = task, # A Callable (function) which is gonna be executed by Thread
args = ("Uncle John",), # positional arguments to be passed to target function
kwargs = {"l_name":"Uncle John"} # positional arguments to be passed to target function
)

# The thread is created and task is also assigned but hasn't start working yet

thread.start() # this will start the `CustomThread`

print("Here main thread continues its execution.")

executing_thread = current_thread()

print(f"Message by {executing_thread.name}")

Another way of creating the thread is using Inheritance, Let's see how

from threading import Thread, current_thread
from time import sleep

class MyClass(Thread): # inherited the Thread class
def __init__(self, thread_name:str) -> None:
super().__init__(name = thread_name) # invoking Thread class constructor

@staticmethod
def task(f_name:str, l_name:str) -> None:
"""
This is a simple function which greets the provided name
:param:
f_name -> a string of any length
l_name -> a string of any length
:return:
None -> Simply nothing
"""

executing_thread = current_thread() # return the current thread object

print(f"Execution of task is started by {executing_thread.name}")

sleep(5) # puts the thread in waiting/blocked state for 5 secs.

print(f"Hello {f_name} {l_name} by {executing_thread.name}")

# overriding the run method is equal to assigning the target
def run(self) -> None:
"""
whatever method or function you invoke in this method will be executed by
a new thread.

By this way you may assign multiple tasks to a single thread
"""
self.task("Uncle","John")
self.task("Uncle","Bob")


my_object = MyClass("CustomThread") # The Thread is created, isn't it so simple

my_object.start() # this start execution of your task using a new Thread

Summary

To sum it up, in Python, threading is like having multiple workers (threads) doing different jobs at the same time. The program creates a custom thread to perform a specific task concurrently with the main thread. Each thread works independently, allowing the main thread to continue its own tasks. Threading is a handy tool to make programs faster by multitasking effectively.

Related Video https://www.youtube.com/watch?v=GCsCnBnXly8

Official Website https://pythonbricks.pythonanywhere.com/

Youtube Channel https://www.youtube.com/@PythonBricks

Telegram https://t.me/pythonbricks

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.

--

--