Sobes.tech
Junior — Middle

How have you implemented synchronization between threads using semaphores or their equivalents in various programming languages?

sobes.tech AI

Answer from AI

Semaphores are used to control access to shared resources between threads, limiting the number of threads that can execute a certain section of code simultaneously.

In Python, there is a Semaphore class from the threading module:

import threading

# Create a semaphore with a maximum of 2 permits
sem = threading.Semaphore(2)

def worker(num):
    print(f"Thread {num} is waiting for the semaphore")
    with sem:  # Acquire the semaphore
        print(f"Thread {num} has entered the critical section")
        # Work with shared resource here
        import time
        time.sleep(1)
    print(f"Thread {num} has exited the critical section")

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

for t in threads:
    t.join()

In other languages, such as Java, there is a Semaphore class from java.util.concurrent, which works on a similar principle.

Thus, semaphores allow controlling the number of threads working simultaneously, preventing race conditions and ensuring proper synchronization.

How have you implemented synchronization between… - sobes.tech