简体   繁体   中英

POSIX: value of a semaphore after exiting sem_wait()

A semaphore is initialised with value 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. 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
  • 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). also that way, the final value would be 0 in both cases

Is there a way to solve this discrepancy in 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 .

From man sem_wait() ( italics by me):

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 (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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