POSIX:退出sem_wait()后信号量的值

POSIX: value of a semaphore after exiting sem_wait()

信号量初始化为值 0。

sem_t sem;
sem_init(&sem, 0, 0);

一行执行等待信号量,而另一行将其解锁。一、服务员要等的情况

// value is 0
sem_wait(&sem);  // blocks
                                    // value is 0
                                    sem_post(&sem);
                                    // value becomes 1
// unblocked

二、服务员不用等的情况

                                    // value is 0
                                    sem_post(&sem);
                                    // value becomes 1

// value is 1
sem_wait(&sem);  // does not block
// value has become 0

问题是 sem 的最终值在两种情况下不同:第一种情况为 1,第二种情况为 0。这是一种竞争条件。

理想情况下,问题不会发生,如果:

有没有办法解决 POSIX 中的这种差异?

我会说你对第一种情况的最终假设是错误的。

从对 sem_wait() 的阻塞调用返回时,信号量会递减,因此它最终的值为 0

来自 man sem_wait()斜体 由我):

sem_wait() decrements (locks) the semaphore pointed to by sem. If the semaphore's value is greater than zero, then the decrement proceeds, and the function returns, immediately. If the semaphore currently has the value zero, then the call blocks until either it becomes possible to perform the decrement (i.e., the semaphore value rises above zero), or a signal handler interrupts the call.

上面的措辞与 wording used by POSIX 不同,但这有助于阐明信号量的 "value" 如何与信号量锁定状态相关联。