Sobes.tech
Junior — Middle

How to implement parallel task execution in threads in Python without using processes?

sobes.tech AI

Answer from AI

For parallel execution of tasks in threads in Python without using processes, you can use the threading module. It allows creating and running multiple threads within a single process.

Example of parallel execution of two functions in threads:

import threading
import time

def task(name, delay):
    for i in range(3):
        print(f"{name} is running {i+1} time")
        time.sleep(delay)

thread1 = threading.Thread(target=task, args=("Thread 1", 1))
thread2 = threading.Thread(target=task, args=("Thread 2", 1.5))

thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("All threads are finished")

It is important to remember that due to GIL (Global Interpreter Lock) in CPython, threads do not provide true parallelism when executing CPU-intensive tasks, but they are excellent for I/O-bound tasks.