Sobes.tech
Junior — Middle

How is parallel code execution implemented in Python using threads?

sobes.tech AI

Answer from AI

In Python, parallel execution of code using threads is implemented through the threading module. It allows creating and running multiple threads that execute simultaneously.

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, it is important to consider that due to GIL (Global Interpreter Lock), in standard CPython, threads do not provide true parallelism for CPU-bound tasks, but they are well-suited for I/O-bound operations.