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

标签 multithreading algorithm operating-system

我无法理解 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/

相关文章:

创建一个用 C 语言执行多个命令的程序

python - wx.lib.editor 中的线程

c# - 此代码段中的竞争条件在哪里? (简而言之,来自 C# 5.0)

c++ - 如果不同的线程正在调用另一个不同线程的相同信号,Qt 中是否需要互斥锁?

android - AsyncTask 线程永不消亡

c - 为什么在 C 中将编译和链接过程分开很重要?

algorithm - 修剪杂散节点的大图

algorithm - 给定一个系数向量和一个值,计算多项式的最快方法是什么?

ruby - 通过任意查询查找项目

c - vfork() 系统调用中的返回值