Skip to content

Semaphore

Pranav V R edited this page Jun 23, 2024 · 1 revision

A semaphore is a synchronization primitive in programming that controls access to a shared resource in a concurrent system. It acts as a counter that restricts the number of concurrent threads accessing the resource.

Types of semaphores

  • Counting semaphore
  • Binary semaphore (Mutex)

Counting semaphore

These allow a fixed number of threads to access a resource simultaneously. The semaphore maintains a count of available resources. Threads can acquire resources (decrement the count) and release resources (increment the count). If the count is zero, threads attempting to acquire resources will block until resources become available.

Binary Semaphore (Mutex)

These are simpler semaphores with only two states: locked (1) and unlocked (0). They are often used for mutual exclusion, where only one thread can access a resource at a time. Binary semaphores can be used to implement critical sections to prevent race conditions.

Uses of semaphores

Control Access to Resources

They ensure that only a limited number of threads can access a shared resource concurrently. This helps prevent issues like race conditions or resource exhaustion.

Synchronize Threads

Semaphores provide mechanisms for threads to signal each other, allowing them to coordinate their execution and avoid conflicts.

Example Use Cases

  • Thread Pool Management: Limiting the number of concurrent tasks executed by a thread pool.
  • Database Connection Pooling: Limiting the number of concurrent database connections.
  • Resource Pooling: Limiting access to a finite set of resources like files, network connections, etc.
  • Producer-Consumer Problem: Coordinating producers and consumers to access a bounded buffer.
  • Readers-Writers Problem: Managing concurrent read and write access to a shared data structure.

Clone this wiki locally