Published on

Understand Multithreading in Python in less than 5 minutes

Authors
multi-thread

In this article, We'll try to understand multithreading in very simple terms

Introductory section

Let us explain a bit more few terms before going deeper

  • A program is simply a sequence of statements that has the objective to perform some task. A program is usually stored on the disk
  • A process is a running instance of a program along with all the resources it needs to operate. It has its own memory space.
  • A thread is a sequence of instructions within a program that can be executed independently by a computer's CPU. A program can have multiple threads running at the same time, each performing a specific task

What is multithreading ?

Multithreading simply is a powerful technique that allows a program to execute multiple tasks concurrently. When a python program is executed, it runs in a single thread by default. However, with multithreading, a program can create multiple threads that can execute different parts of the program simultaneously. This can improve performance by utilizing the available processing power more efficiently.

Multi-thread

How to implement multithreading ?

Multithreading is implemented in Python by using the built-in library threading. First, you need to import the threading module. Then, you can create a new thread by creating an instance of the Thread class. Here is a simple example :

import threading

def my_function():
    # code to be executed by the thread

my_thread = threading.Thread(target=my_function)

    # Once the thread is created, we can start it by calling .start() method
my_thread.start()

Here is a more elaborate example of computing the factorial of a list of numbers using multithreading.

import threading
import time

def calculate_factorial(n):
    result = 1
    for i in range(1, n+1):
        result *= i
    print(f"Factorial of {n} is {result}")

numbers = [5, 10, 15, 20]

# create a thread for each number's factorial cal:culation
threads = []
for number in numbers:
    thread = threading.Thread(target=calculate_factorial, args=(number,))
    threads.append(thread)

# start all threads
for thread in threads:
    thread.start()

# wait for all threads to finish
for thread in threads:
    thread.join()

print("All factorials calculated!")

Steps to follow to implement multithreading

  • Create thread by creating an instance of the Thread class. Each thread should be tagged to a Python function with the arguments to pass to that function
  • Start task execution with start()
  • Wait for thread to complete execution with join(). In the above example, we waited for all the threads to finish before printing the message All factorials calculated!

Final notes

In conclusion, multithreading is a powerful technique that can enhance the performance of Python programs by executing multiple tasks concurrently. It allows for better resource utilization, improved performance, and enhanced user experience. It is important to keep in mind that multithreading also comes with some potential drawbacks, such as race conditions, deadlocks, and other synchronization issues. Therefore, it is crucial to design and implement multithreaded applications with care and attention to detail.

Not all concepts are explained in this article. To get more details, the threading library documentation as well as this article are good reads.