Skip to main content
  1. Notes/
  2. Multithreading/

Semaphores

Difference between Semaphores and Mutexes
#

  • Mutex (Mutual exclusion) is more of an access control mechanism, whereas Semaphore is more of a signaling mechanism.
  • The one who locked a resource should be the one who unlocks it in case of a Mutex.
  • In case of a Semaphore, any thread can signal (increment) the semaphore, not necessarily the one who waited (decremented) it.

Semaphores
#

  • Semaphore lives in a memory location shared by all the processes that need to synchronize their operations.

  • It is basically an integer variable, which is greater than or equal to zero.

  • It can be initialized to a non-negative integer value.

  • Two atomic operations are defined on the semaphore:

    • wait (also called P, down, or decrement) - it waits until the semaphore value is > 0, then decrements it by 1, and if the value is 0, it blocks the process until it becomes > 0

      P(semaphore S) {
          while(S<=0) // keep going until S>0
            ; // no operation
          S--; // at the end, decrement S
      }
      knock! knock!
      • This is just a busy-wait implementation of the wait operation, for the sake of simplicity. This implementation is more of a spinlock, than a semaphore.
      • In real-world implementations, the process would be put to sleep instead of busy-waiting, to avoid wasting CPU cycles.
  • signal (also called V, up, or increment) - it increments the semaphore value by 1

    V(semaphore S) {
        S++; // increment S
    }

    NOTE: P - from Dutch word proberen meaning “to test” and V - from Dutch word verhogen meaning “to increment”

  • POSIX semaphore library has two functions for this:

    • sem_wait(sem_t *sem) - performs the wait operation
    • sem_post(sem_t *sem) - performs the signal operation

References
#