Multithreading in Python

Posted by Afsal on 22-Mar-2024

Hi Pythonistas!

Today we will learn about multithreading in Python. Multithreading in Python allows you to run multiple threads (smaller units of a process) concurrently. Threads are more appropriate for I/O-bound tasks where the program spends a significant amount of time waiting for external resources, such as network requests or file I/O. However, due to the Global Interpreter Lock (GIL) in CPython (the standard Python implementation), threads are not suitable for CPU-bound tasks that require parallel execution.

We use threading module for threading. Let us learn this with an example

Create new thread

import threading
thread = threading.Thread(target=<callable>, args=<argument to function>)

Start a thread

thread.start()

Join a thread

thread.join()

When the join method is called then the thread is joined to the parent thread

Let us check with a example

Example without thread

import threading
import time

def print_numbers():
    for i in range(5):
        time.sleep(1)
        print(f"print_numbers : {i}")

def print_letters():
    for letter in 'ABCDE':
        time.sleep(1)
        print(f"print_letters: {letter}")


print('without thread')
start_time = time.time()
print_numbers()
print_letters()
print("Time taken without thread: ", time.time()-start_time)

Output

without thread

print_numbers : 0

print_numbers : 1

print_numbers : 2

print_numbers : 3

print_numbers : 4

print_letters: A

print_letters: B

print_letters: C

print_letters: D

print_letters: E

Time taken without thread:  10.010527610778809

With thread

thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

start_time =  time.time()
thread1.start()
thread2.start()


thread1.join()
thread2.join()
print("Time taken with thread: ", time.time()-start_time)

Output

print_numbers : 0

print_letters: A

print_numbers : 1

print_letters: B

print_numbers : 2

print_letters: C

print_numbers : 3

print_letters: D

print_numbers : 4

print_letters: E

Time taken with thread:  5.006333351135254

When to use

  • File I/O Operations
  • Network Communication
  • GUI Applications

threads are not suitable for CPU-bound tasks that require parallel execution

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in