Akashdeep Saluja
Akashdeep Saluja

Reputation: 3089

Confusion over implementation of wait() operation for semaphore

I am not able to understand the atomic operations in wait(). The wait() operation is implemented this way in many of the sources/books:

wait(S) {
  while S <= 0;
  S--;
}

If operations such as S--, S<=0, and signal op which is S++ are atomic. Even then two threads might decrement S value. And then the whole idea of using semaphore is lost.

I even found some support from Wikipedia which gives implementation of wait() as below, and says that if block including S-- is atomic. And to me it makes complete sense.

wait(S) {
    while true:
       [ if S<= 0:
            S--;
       ]

Any thoughts over first implementation of wait(). Am I missing some thing.

Upvotes: 1

Views: 207

Answers (1)

Sumeet
Sumeet

Reputation: 8292

The semaphore S apart from initialization can only be accessed through signal and wait operations.

Even then two threads might decrement S value. And then the whole idea of using semaphore is lost.

No, it is not possible. The only thing that is possible is that multiple threads can try to decrement the value of S.

Suppose multiple threads are waiting in the while loop. This means that S is 0. As soon as signal is executed, S becomes 1 and the condition

while S <= 0

becomes false. And only one thread will successfully execute the S-- statement. To quote the bible of operating system Operating systems principles by Galvin,silberschatz and gagne

All the modifications to the integer value of the semaphore in the wait() and signal() operations must be executed indivisibly. That is, when one process modifies the semaphore value, no other process can simultaneously modify that same semaphore value. In addition, in the case of wait(S), the testing of the integer value of S<=0, and its possible modification S--, must also be executed without interruption.

Upvotes: 2

Related Questions