Semaphore

Semaphore is a signalling mechanism, and a thread which is waiting on the semaphore can be signaled by another thread. Semaphore is typically a variable used to solve critical section problems and to achieve process synchronization in multi-processing/multi-threading environment.

Example – Imagine a bathroom with 4 identical toilets here, identical keys can open the bathrooms. Here as many as 4 people can use the bathroom simultaneously and they wait and signal one another about the occupancy of the bathrooms.

Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." 
Ref: Symbian Developer Library



Semaphore locking has a time limit to prevent a deadlock. Scholten’s semaphore is referred to as the General or Counting Semaphore, Dijkstra’s being known as the Binary Semaphore.

1. Counting Semaphore (signal/wait)
When number of resources a Semaphore protects is greater than 1, it is called a Counting Semaphore

2. Binary Semaphore (lock/unlock)
When it controls one resource, it is called a Boolean Semaphore. A boolean semaphore is equivalent to a mutex.

Semaphores which are restricted to the values 0 and 1 (lock/unlock, available/unavailable) are referred to as binary semaphore and are used to implement locks. On the other hand, Semaphores which allow an arbitrary resource count are referred to as counting semaphore.

Disadvantages 

  • Semaphore programming is a complex method and therefore chances of not achieving mutual exclusion are high.
  • Semaphore is more prone to errors
  • The operating system has to keep track of all calls to wait and signal semaphore.
  • Chances of deadlock are high in semaphore incase the wait and signal operations require to be executed in the correct order.

Advantages 

  • Does not allow multiple processes to enter critical section.
  • It allows more than one thread to access the critical section.
  • They allow efficient management of resources.
  • There is no wastage of process time and resources in semaphore due to busy waiting.

Thread Synchronization 

https://www.tutorialspoint.com/how-to-use-posix-semaphores-in-c-language

Process Synchronization 


https://www.geeksforgeeks.org/petersons-algorithm-in-process-synchronization/?ref=rp

Reference :

Comments