简体   繁体   English

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

[英]POSIX: value of a semaphore after exiting sem_wait()

A semaphore is initialised with value 0. 信号量初始化为值0。

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

One line of execution waits on the semaphore, while another one unlocks it. 执行的一行等待信号量,而另一行则将其解锁。 First, a case where the waiter has to wait. 首先,是服务生必须等待的情况。

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

Second, a case where the waiter does not have to wait. 第二,服务员不必等待的情况。

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

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

The problem is that the final value of sem is different in the two cases: 1 in the first case and 0 in the second one. 问题在于sem的最终值在两种情况下是不同的:第一种情况下为1,第二种情况下为0。 It is a sort of race condition. 这是一种比赛条件。

Ideally the problem would not occur if: 理想情况下,在以下情况下不会发生此问题:

  • when the value of the semaphore is 0 and sem_wait() is called, the value would become -1, rather than staying 0. That way, the final value would be 0 in both cases 当信号量的值为0并sem_wait() ,该值将变为-1,而不是保持为0。这样,两种情况下的最终值都将为0。
  • or, a variant of sem_post() existed, that would wake one process or increment the value (if there are processes waiting, the value would not be incremented). 或者,存在sem_post()的变体,它将唤醒一个进程增加该值(如果有正在等待的进程,则该值不会增加)。 also that way, the final value would be 0 in both cases 同样,两种情况下的最终值均为0

Is there a way to solve this discrepancy in POSIX? 有没有办法解决POSIX中的这种差异?

I'd say your final assumptions for the 1st case is wrong. 我会说您对第一种情况的最终假设是错误的。

On returning from a blocked call to sem_wait() the semaphore gets decremented, so it ends up with a value of 0 . 从阻塞调用返回sem_wait() ,信号量会递减,因此最终的值为0

From man sem_wait() ( italics by me): 来自man sem_wait() (我的斜体字 ):

sem_wait() decrements (locks) the semaphore pointed to by sem. sem_wait()递减(锁定)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 (ie, the semaphore value rises above zero), or a signal handler interrupts the call. 如果信号灯当前的值为零,则调用将阻塞, 直到有可能执行减量操作 (即信号灯值升至零以上),或者信号处理程序中断该调用为止

This above wording is different from the wording used by POSIX , however this helps to shed some light on how the semaphore's "value" correlates to the semaphores locking state. 上面的措词不同于POSIX所使用措词 ,但是,这有助于阐明信号量的“值”如何与信号量锁定状态相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM