信号量 P 和 V 操作是原子操作吗?

发布于 2024-10-19 01:12:38 字数 59 浏览 2 评论 0原文

可以在信号量上执行的 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()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╭⌒浅淡时光〆 2024-10-26 01:12:38

假设我们有一个二进制信号量 s,其值为 1,并且两个进程同时尝试在 s 上执行 P。这些操作中只有一个能够在 s 上的下一个 V 操作之前完成;尝试执行 P 操作的另一个进程被挂起。

摘自我的大学笔记:

我们可以认为如果P和V作为控制
访问资源:

当一个进程想要使用
资源,它执行P操作:
如果成功,它会减少
可用资源量和
过程继续;如果所有的
资源当前正在使用中,
进程必须等待。

当一个进程完成时
资源,它执行V操作:
如果有进程在等待
资源,其中之一被唤醒;
如果没有等待进程,
信号量增加
表明现在有更多的
资源免费。请注意,
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:

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.

暮色兮凉城 2024-10-26 01:12:38

如果我没记错的话,是的。它们需要确保一个线程无法在另一个线程获取资源时获得资源。如果不是,则意味着两个线程可以开始访问资源,然后被切换出 CPU,而另一个进程可以访问该资源。这会严重扰乱事情。

有关详细信息,请参阅此处:http://en.wikipedia.org/wiki/Semaphore_ (编程)#Semantics_and_Implementation

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文