Does Python support multi-threading?
Does Python support multi-threading?
Does Python support multithreading? If yes, Give me an example.
Farjanul Nayem Answered question June 21, 2023
Yes, Python supports multithreading. Python’s standard library provides a module called threading
that allows you to create and manage threads in your programs.
However, it’s important to note that due to the Global Interpreter Lock (GIL) in CPython (the reference implementation of Python), multithreading in Python may not always result in true parallel execution across multiple CPU cores. The GIL prevents multiple native threads from executing Python bytecodes at the same time, effectively limiting the parallelism of CPU-bound tasks.
import threading import time def print_1(): print("Before the delay") time.sleep(5) print("Hello 1") def print_2(): print("Hello 2") if __name__ =="__main__": # creating thread t1 = threading.Thread(target=print_1) t2 = threading.Thread(target=print_2) # starting thread 1 t1.start() # starting thread 2 t2.start() # wait until thread 1 is completely executed t1.join() # wait until thread 2 is completely executed t2.join() print("Done!")
Farjanul Nayem Changed status to publish June 21, 2023