Sobes.tech
Junior — Middle

What is the purpose of a semaphore in Python, and in which cases should it be used?

sobes.tech AI

Answer from AI

A semaphore in Python is a synchronization mechanism from the threading module that limits the number of threads executing a certain section of code simultaneously. It maintains a counter that decreases when entering the critical section and increases when leaving.

Semaphores are useful when you need to control access to a limited resource, such as a connection pool or files, to prevent exceeding a set number of concurrent operations.

Example of using a semaphore:

import threading
import time

sem = threading.Semaphore(3)  # maximum 3 threads at the same time

def worker(num):
    with sem:
        print(f"Thread {num} entered")
        time.sleep(2)
        print(f"Thread {num} exited")

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    t.start()
    threads.append(t)

for t in threads:
    t.join()

In this example, only 3 threads can work simultaneously, others wait for the semaphore to be released.