Parallel programming - Semaphore (Counter Variable)


A semaphore is a variable that control the access (physical or logical) by multiple thread to a common resource.

A semaphore is a data structure that is initialized to a positive integer value and that can be locked multiple times. As long as the semaphore value is positive, locking it will return the current value and the locking process will continue execution immediately; the semaphore will be decremented upon locking. Releasing the lock will increment the semaphore again.

Once the semaphore has reached zero, the next process that attempts to acquire a lock will be suspended until another process releases its lock and this increments the semaphore again.

They are used for synchronization between two or more processes.

Example / Usage


If the stoplight is green, a train can enter the train station. If it is yellow or red (or any other color), the train station cannot be accessed.

Connection Pool

To implement a connection pool.

When an application supports maximum 10 connection, a semaphore with the value 10 will be created.

  • Whenever the application creates a connection, the semaphore will be decremented by 1.
  • Whenever the application disconnect a connection, the semaphore will be incremented by 1.
  • When the semaphore is above 10, the application will wait or return a message.

Process Resource Limitation

With a semaphore, you limit the resources for a process such as the number of Open File, CPU, .. for:


Documentation / Reference

Powered by ComboStrap