问题
Can multiple threads wait on a single semaphore ? If yes, upon semaphore down which one will be resumed ?
回答1:
As the document for sem_post suggests,
If the value of the semaphore resulting from this operation is zero, then one of the threads blocked waiting for the semaphore will be allowed to return successfully from its call to
sem_wait(). If the symbol_POSIX_PRIORITY_SCHEDULINGis defined, the thread to be unblocked will be chosen in a manner appropriate to the scheduling policies and parameters in effect for the blocked threads. In the case of the schedulersSCHED_FIFOandSCHED_RR, the highest priority waiting thread will be unblocked, and if there is more than one highest priority thread blocked waiting for the semaphore, then the highest priority thread that has been waiting the longest will be unblocked. If the symbol_POSIX_PRIORITY_SCHEDULINGis not defined, the choice of a thread to unblock is unspecified.
Also , as sem_wait defines in Application Usage section, There can be cases of priority inversion involving threads with differemt priority levels
回答2:
Can multiple threads wait on a single semaphore ?
Yes.
If yes, upon semaphore down which one will be resumed ?
Exactly one of them. Which one depends on OS kernel implementation: the container type that is used to hold the waiting threads. This is quite likely to be a FIFO queue and so the first thread to call semaphore.wait() will be released first, but you should not design your app in any way that relies on this behaviour.
回答3:
That will be the thread scheduled to execute at that particular CPU cycle.
来源:https://stackoverflow.com/questions/16163932/multiple-threads-can-wait-on-a-semaphore-at-same-time