信号量P和V操作是原子吗? [英] Are Semaphore P and V operations atomic?
问题描述
能够对信号量保证原子执行的P()和V()操作吗?一个信号量阻止两个进程进入P()?
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,并且两个进程同时尝试执行P on。只有其中一个操作能够在下一个V操作之前完成;
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:
我们可以认为如果P和V控制
访问资源:
We can think if P and V as controlling access to a resource:
当进程要使用
资源,它执行P操作:
如果成功,它减少
的可用资源量,并且
进程继续;如果所有
资源当前正在使用,则
进程必须等待。
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.
当进程完成
资源时,它执行V操作:
如果有进程在
资源上等待,其中一个被唤醒;
如果没有等待进程,
信号量增加
,表明现在有更多的
资源空闲。注意,V的
定义没有指定如果多个
进程在同一个
信号量上暂停,那么哪个
进程被唤醒。
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可以解决互斥和条件同步问题。因此,您的问题的答案是:是的。
Semaphores can solve both mutual exclusion and condition synchronization problems. So the answer to both your questions is: yes.
这篇关于信号量P和V操作是原子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!