Multiple threads can wait on a semaphore at same time

风格不统一 提交于 2020-01-03 03:32:10

问题


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_SCHEDULING is 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 schedulers SCHED_FIFO and SCHED_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_SCHEDULING is 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!