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.
The following code snippet shows how to create threads using the threading module in python:
# importing the threading moduleimport threading# importing the time moduleimport time# Function to print "Hello", however, the function sleeps# for 2 seconds at the 11th iterationdef print_hello():for i in range(20):if i == 10:time.sleep(2)print("Hello")# Function to print numbers till a given numberdef 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 threadsthread1.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:
thread1 and thread2 are created and started.thread1 starts executing.thread1 goes to sleep, and thread2 starts executing, finishing up before the next context switch.thread2 resumes execution and finishes.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 thread, whose join() method is called, is terminated:
# importing the threading moduleimport threading# importing the time moduleimport time# Function to print "Hello", however, the function sleeps# for 2 seconds at the 11th iterationdef print_hello():for i in range(20):if i == 10:time.sleep(2)print("Hello")# Function to print numbers till a given numberdef 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 threadsthread1.start()thread2.start()thread1.join()thread2.join()print("It's the main thread again!")print("Threads 1 and 2 have finished executing.")
Free Resources