Are Semaphore P and V operations atomic?

Aditya369 picture Aditya369 · Feb 23, 2011 · Viewed 9.3k times · Source

Are the P() and V() operations that can be performed on a semaphore guarantee atomic? Can a semaphore prevent two processes getting into the P()?

Answer

Dhruv Gairola picture Dhruv Gairola · Feb 23, 2011

Suppose we have a binary semaphore, s, which has the value 1, and two processes simultaneously attempt to execute P on s. Only one of these operations will be able to complete before the next V operation on s; the other process attempting to perform a P operation is suspended.

Taken from my university notes:

We can think if P and V as controlling access to a resource:

When a process wants to use the resource, it performs a P operation: if this succeeds, it decrements the amount of resource available and the process continues; if all the resource is currently in use, the process has to wait.

When a process is finished with the resource, it performs a V operation: if there were processes waiting on the resource, one of these is woken up;
if there were no waiting processes, the semaphore is incremented indicating that there is now more of the resource free. Note that the definition of V doesn’t specify which process is woken up if more than one process has been suspended on the same semaphore.

Semaphores can solve both mutual exclusion and condition synchronization problems. So the answer to both your questions is: yes.