Are Semaphore P and V operations atomic?

冷暖自知 提交于 2019-12-10 01:54:41

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5094440/are-semaphore-p-and-v-operations-atomic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!