c++ - 使基于选择的循环尽可能响应

标签 c++ multithreading select

此线程对网络事件非常敏感,但可以保证每秒处理消息队列的频率仅为 100 次。我可以继续减少超时,但在某个时间点之后我将忙于等待并消耗 CPU。在不切换到另一种方法的情况下,这个解决方案真的和我能得到的一样好吗?

// semi pseudocode
while (1) {
  process_thread_message_queue(); // function returns near-instantly
  struct timeval t;
  t.tv_sec = 0;
  t.tv_usec = 10 * 1000; // 10ms = 0.01s
  if (select(n,&fdset,0,0,t)) // see if there are incoming packets for next 1/100 sec
  {
    ... // respond with more packets or processing
  }
}

最佳答案

这取决于您的操作系统为您提供的功能。在 Windows 上,您可以使用 MsgWaitForMultipleObjectsEx 等待线程消息和一堆句柄同时。这解决了你的问题。在其他操作系统上,您应该有类似的东西。

关于c++ - 使基于选择的循环尽可能响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5387697/

相关文章:

c++ - std::thread 访问从共享库加载的函数

c++ - 错误 LNK1104 : cannot open file 'DFOR.lib' Visual Studio

c++ - C和C++文件读取性能比较

c - FIFO 管道在 select() 中始终可读

mysql - 将一个表的值关联到另一个表

c++ - 我的 if 、 else if 和 else 循环有什么问题?

android - unity3d - Android 的独立 UI 线程

c# - 无法理解 : using lock () but never executing code

multithreading - Golang sleep 线程而不是忙于等待

html - Angularjs 选择对象的 ng-model 绑定(bind)