A thread is a unit of execution within a process. A process can contain one or more threads.
Multithreading refers to concurrently executing multiple threads. This is done by 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.
import threading import time def print_hello(): for i in range(10): if i == 5: time.sleep(2) print("Hello World") def print_numbers(num): for i in range(num+1): print(i) print("The main thread.") thread1 = threading.Thread(target = print_hello, args = ()) thread2 = threading.Thread(target = print_numbers, args = (7,)) # Starting the two threads thread1.start() thread2.start() print("Main thread again!")
In the above code, first the main thread executes. This will print ‘The main thread’ and then threads
thread2 are created and started. A context switch occurs, and
thread1 starts executing. After the first five iterations,
thread1 goes to sleep, and
thread2 starts executing, finishing up before the next context switch.
Now, the main thread gains control of the CPU and prints ‘Main thread again!’. Another context switch takes place, and
thread2 resumes execution and finishes.
Since there are no more instructions to be executed by the main thread, the program terminates.
Try out the above code and understand the output you get.