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()?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With