开发者

Are Semaphore P and V operations atomic?

开发者 https://www.devze.com 2023-02-13 04:06 出处:网络
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, w

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

0

精彩评论

暂无评论...
验证码 换一张
取 消