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?
Advertisement
Answer
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 }