Search code examples
operating-systemsemaphore

What is the purpose of the while loop in semaphore wait( ) function? Can it be replaced with an if statement?


I'm learning about Semaphores in Operating Systems and I don't understand the purpose of the empty while loop.

The code is from my textbook, and I can see that the while(s <= 0) is followed by a ';' so basically do: nothing, and then the s-- line. I don't understand the purpose or meaning of this, would it be any different if it was if(s <= 0) instead of while?

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

Solution

  • A semaphore is a counter and you can call two functions on it: decrement (also known as wait, p, etc.) and increment (post, signal, v, etc.).

    The following happens when a thread calls wait on a semaphore:

    1. If the semaphore count is greater than 0, the count is decremented by 1 and the call to wait returns.
    2. If the semaphore count is less than or equal to 0, the call to wait will wait for the semaphore count to increase to 1 or more (which will happen when other threads call post on the semaphore), subtract 1 from the count, and return.

    The while loop in your code above is to handle the second case. The function must not return until the count is greater than 0 (which is why the loop condition is S <= 0), so the while loop will continue spinning until this count is greater than 0. The purpose of the while loop is solely to stop the function from advancing. There is no body of code that you want to execute repeatedly.

    An if statement is insufficient to handle this case because it just checks S <= 0 once. The function is able to advance past the if statement even if the count is still less than or equal to 0.

    Please note that the semaphore code in your textbook is a great simplification of how actual semaphores work. Generally, if a thread calls wait and the count is less than or equal to 0, the thread will block on some underlying synchronization primitive (e.g., a futex) and the scheduler will put the thread to sleep until another thread calls post. Thus, there is either no while loop or any while loop present will be a little different than the one in your question. Also, there needs to be some sort of protection mechanism for the integer counter in the semaphore structure. Otherwise, multiple threads can race to increment/decrement the counter and multiple threads may be able to advance past the while loop even if the count is originally 1 (so the semaphore will not protect the critical section properly).