Junior — Middle
Is it possible to run two threads simultaneously in Python and how to implement it?
sobes.tech AI
Answer from AI
Yes, in Python, you can run two or more threads simultaneously using the threading module.
Example of creating and starting two threads:
import threading
import time
def worker(name):
for i in range(3):
print(f"Thread {name} is working {i}")
time.sleep(1)
thread1 = threading.Thread(target=worker, args=("A",))
thread2 = threading.Thread(target=worker, args=("B",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("All threads are finished")
However, keep in mind that due to GIL (Global Interpreter Lock), in standard CPython, threads do not execute in parallel on multiple cores for CPU-bound tasks, but for I/O-bound tasks (like network requests, file reading), multithreading works efficiently.