等待多个信号量而不忙等待(C / C ++ Linux) [英] Waiting on multiple semaphores without busy-waiting (C/C++ Linux)

查看:1515
本文介绍了等待多个信号量而不忙等待(C / C ++ Linux)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有多个信号量,我如何能有一个进程块,直到至少有一个信号量是免费的?我知道我可以使用一个忙等待循环,如:

If I have more than one semaphore, how can I have a process block until at least one of the semaphores is free? I know I can do this with a busy-wait loop such as:

// blocks until one of the semaphores in sems is free, returns
// index of semaphore that was available
int multiple_sem_wait(sem_t **sems, int num_sems) {
   while (true) {
      for (int i = 0; i < num_sems; ++i) {
         if (sem_trywait(sems[i]) == 0) {
            return i;
         }
      }
   }
}

有没有办法做到这一点没有忙循环?

But is there a way to do this without a busy-loop? Perhaps there's some IPC technique other than semaphores that I should be using?

感谢

推荐答案

这里(developers.sun.com)是一篇短文从Sun了解他们如何在Solaris中实现他们的 WaitForMultipleObjects 仿真。基本思想是将条件变量的列表与句柄(由互斥体保护)相关联,并且每当句柄被发信号通知所有条件变量。每次调用模拟的 WaitForMultipleObjects ,一个新的条件变量被创建并添加到您感兴趣的所有句柄的列表中。在 WaitForMultipleObjects emulation,你阻塞条件变量,并在你醒来时检查每个句柄。

Here (developers.sun.com) 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.

为什么有条件列表的原因变量(而不是一个)是你可能有两个线程阻塞在句柄上:线程1在A和B上被阻塞,线程2在A和C上被阻塞。信令B不应该唤醒线程2.由于每个调用到 WaitForMultipleObjects 创建一个新的条件变量,在这种情况下,B和C每个都有一个不同的条件变量,A将有两个条件变量。

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.

这篇关于等待多个信号量而不忙等待(C / C ++ Linux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆