gpt4 book ai didi

multithreading - 对信号量的 wait() 操作的实现感到困惑

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:40:25 26 4
gpt4 key购买 nike

我无法理解 wait() 中的原子操作。 wait() 操作在许多资源/书籍中都是以这种方式实现的:

wait(S) {
while S <= 0;
S--;
}

如果 S--、S<=0 和 S++ 的信号操作等操作是原子的。 即使这样,两个线程也可能会递减 S 值。然后使用信号量的整个想法就丢失了。

我什至从 Wikipedia 找到了一些支持它给出了 wait() 的实现,如下所示,并表示如果包含 S-- 的 block 是原子的。对我来说,这是完全有道理的。

wait(S) {
while true:
[ if S<= 0:
S--;
]

关于首次实现 wait() 的任何想法。我是不是漏掉了什么。

最佳答案

信号量S除初始化外,只能通过signalwait操作访问。

Even then two threads might decrement S value. And then the whole idea of using semaphore is lost.

不,这是不可能的。唯一可能的是多个线程可以尝试减少 S 的值。

假设有多个线程在 while 循环中等待。这意味着 S0signal 执行后,S 变为 1 并且条件

while S <= 0

变成假的。而只有一个线程会成功执行S--语句。引用操作系统圣经 Galvin,silberschatz 和 gagne 的 Operating systems principles

All the modifications to the integer value of the semaphore in the wait() and signal() operations must be executed indivisibly. That is, when one process modifies the semaphore value, no other process can simultaneously modify that same semaphore value. In addition, in the case of wait(S), the testing of the integer value of S<=0, and its possible modification S--, must also be executed without interruption.

关于multithreading - 对信号量的 wait() 操作的实现感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43018014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com