October 13, 2024

Python Semaphore

A Semaphore in Python is a synchronization primitive that is used to control access to a shared resource by multiple threads. It is part of the threading module and helps manage concurrent access by limiting the number of threads that can access a resource at the same time.

1. Introduction to Semaphore

A semaphore maintains a counter that is decremented when a thread acquires the semaphore and incremented when a thread releases it. If the counter is zero, threads that try to acquire the semaphore will be blocked until a thread releases it.

2. Using Semaphore in Python

The Semaphore class in the threading module is used to create semaphore objects. Here’s a basic example:

Example: Basic Usage of Semaphore

import threading
import time

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

def worker(number):
    print(f"Worker {number} is trying to acquire the semaphore...")
    semaphore.acquire()
    print(f"Worker {number} acquired the semaphore!")
    time.sleep(2)  # Simulate work
    print(f"Worker {number} is releasing the semaphore.")
    semaphore.release()

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

# Wait for all threads to finish
for thread in threads:
    thread.join()
    

3. Semaphore Methods

The Semaphore class provides the following methods:

  • acquire(blocking=True, timeout=None): Acquire a semaphore. If blocking is True, the call will block until the semaphore is available. If timeout is specified, it will wait for the semaphore to be available for up to the given timeout.
  • release(): Release the semaphore, incrementing the internal counter by one. If there are waiting threads, one of them will be unblocked.

4. Conclusion

Semaphores are useful for controlling access to shared resources in multithreaded applications. They help prevent race conditions and ensure that only a specified number of threads can access a resource simultaneously.