Reputation: 13
this is my code:
wait(){
while(S<=0)
//puts the thread in the block list until it wakes up(by calling post)
S = S-1
}
there is a while loop in the wait function of a semaphore, can't I use an if statement simply?
Upvotes: 0
Views: 991
Reputation: 180073
Why is there a while loop in wait function of a semaphore, when if can be used too?
I take the
//puts the thread in the block list until it wakes up(by calling post)
comment as a place-holder for code that really does do what the comment describes, and the code overall to be meant as schematic for an implementation of a semaphore (else there is no semaphore to be found in it, and the [linux-kernel] tag also inclines me in this direction). In that event ...
Consider the case that two threads are blocked trying to decrement the semaphore. A third thread increments the semaphore to value 1, causing both of the first two to unblock. Only one of erstwhile-blocked threads can be allowed to decrement the semaphore at that point, else its value would drop below zero. The other needs to detect that it cannot proceed after all, and go back to waiting. That's what the loop accomplishes.
Upvotes: 1
Reputation: 264331
Because we can't assume that after a thread is woken up and it requires the lock another thread has not already come along and taken the resource this is guarding:
wait(){
Some lock_guard(mutex); // You lock here.
while(S<=0) {
condition.wait(lock_guard); // While you wait here
// the lock is released.
// when the condition/semaphore is signalled
// one or more threads may be released
// but they must aquire the lock before
// they return from wait.
//
// Another thread may enter this function
// aquire the lock and decrement S below
// before the waiting thread aquires the
// lock and thus mustbe resuspended.
}
S = S-1
}
Upvotes: 2
Reputation: 24
What you have here is called active waiting. Thread or process waits for variable S to change it value to 1 in order to access critical section. One IF would only check once and then go to futher instruction (in this case instruction from critical section, which would be huge error). Thats why it should wait in loop - in order to actually wait, not only check condition once.
But your code is not doing what you think it does.
while(S == 0) {}
or
while(S == 0);
would do the work. Your code constantly does S = S - 1 and with your condition it creates infinite loop. S in semaphores should never go lower than 0, as it would mean that one thread went to critical section without permisson.
Upvotes: 0