What is multithreading in Python?

A thread is a unit of execution within a process. Multithreading refers to concurrently executing multiple threads by rapidly switching the control of the CPU between threads (called context switching).

The Python Global Interpreter Lock limits one thread to run at a time even if the machine contains multiple processors.​

Codes

Creating threads

The following code snippet shows how to create threads using the threading module in python:

# importing the threading module
import threading
# importing the time module
import time
# Function to print "Hello", however, the function sleeps
# for 2 seconds at the 11th iteration
def print_hello():
for i in range(20):
if i == 10:
time.sleep(2)
print("Hello")
# Function to print numbers till a given number
def print_numbers(num):
for i in range(num+1):
print(i)
# Creating the threads. Target is set to the name of the
# function that neeeds to be executed inside the thread and
# args are the arguments to be supplied to the function that
# needs to be executed.
print("Greetings from the main thread.")
thread1 = threading.Thread(target = print_hello, args = ())
thread2 = threading.Thread(target = print_numbers, args = (10,))
# Starting the two threads
thread1.start()
thread2.start()
print("It's the main thread again!")

Let’s try to make sense of the output by tracing the execution of the code:

  1. The main thread executes. “Greetings from the main thread” is printed, threads thread1 and thread2 are created and started.
  2. A context switch occurs, and thread1 starts executing.
  3. After the first ten iterations, thread1 goes to sleep, and thread2 starts executing, finishing up before the next context switch.
  4. Now, the main thread gains control of the CPU and prints “It’s the main thread again!”
  5. Another context switch takes place, and thread2 resumes execution and finishes.
  6. Since there are no more instructions to be executed by the main thread, the program terminates.

Using thread.join()

What if it was required to block the main thread until thread1 and thread2 finished executing? Then thread.join() would come in handy as it blocks the calling thread until the threa​d, whose join() method is called, is terminated:

# importing the threading module
import threading
# importing the time module
import time
# Function to print "Hello", however, the function sleeps
# for 2 seconds at the 11th iteration
def print_hello():
for i in range(20):
if i == 10:
time.sleep(2)
print("Hello")
# Function to print numbers till a given number
def print_numbers(num):
for i in range(num+1):
print(i)
# Creating the threads. Target is set to the name of the
# function that neeeds to be executed inside the thread and
# args are the arguments to be supplied to the function that
# needs to be executed.
print("Greetings from the main thread.")
thread1 = threading.Thread(target = print_hello, args = ())
thread2 = threading.Thread(target = print_numbers, args = (10,))
# Starting the two threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("It's the main thread again!")
print("Threads 1 and 2 have finished executing.")
Copyright ©2024 Educative, Inc. All rights reserved