Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Semaphore P and V operations atomic?

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()?

like image 828
Aditya369 Avatar asked Feb 23 '11 17:02

Aditya369


2 Answers

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.

like image 151
Dhruv Gairola Avatar answered Oct 12 '22 23:10

Dhruv Gairola


If I recall correctly, yes they are. They are required to be to ensure that one thread cannot obtain resources while another thread does. If it wasn't, this would imply that two threads could begin accessing a resource and then be switched out of the CPU and another process could gain access to it instead. This would distrupt things quite a bit.

See here for for more info: http://en.wikipedia.org/wiki/Semaphore_(programming)#Semantics_and_Implementation

like image 30
pseudoramble Avatar answered Oct 13 '22 00:10

pseudoramble