我无法理解 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
除初始化外,只能通过signal和wait操作访问。
Even then two threads might decrement S value. And then the whole idea of using semaphore is lost.
不,这是不可能的。唯一可能的是多个线程可以尝试减少 S
的值。
假设有多个线程在 while 循环中等待。这意味着 S
是 0
。 signal 执行后,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/