Waiting on multiple semaphores without busy-waiting (C/C++ Linux)

白昼怎懂夜的黑 提交于 2019-11-30 22:31:15
vhallac

Here (developers.sun.com, via the Internet Archive) is a short paper from Sun about how they implemented their WaitForMultipleObjects emulation in Solaris. The basic idea is to associate a list of condition variables to a handle (protected by a mutex), and signal all of the condition variables whenever the handle is signaled. Each time you call the emulated WaitForMultipleObjects, a new condition variable is created and added to the list of all handles you are interested in. In the WaitForMultipleObjects emulation, you block on the condition variable, and check each of your handles when you wake up.

The reason why there is a list of condition variables (and not a single one) is that you may have two threads blocking on handles: thread 1 is blocked on A and B, and thread 2 is blocked on A and C. Signaling B should not wake up thread 2. Since each call to WaitForMultipleObjects create a new condition variable, in this scenario, B and C will have one distinct condition variable each, and A will have both condition variables.

For more detailed info, you will need to read the article itself.

Use multiple separate waiter threads, as in:

  • Each thread waits on a separate semaphore.
  • Upon successfully waiting on the semaphore, any given waiter thread signals (via another semaphore, condition variable, or whatever primitive is most convenient) the thread that wants to "wait on multiple semaphores".
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!