在1个线程上运行的boost::asio::io_service如何唤醒等待条件

How could a boost::asio::io_service running on 1 thread wake up awaiting condition

本文关键字:service 条件 唤醒等待 io asio 线程 运行 boost 1个      更新时间:2023-10-16

谢谢你回复Sam Miller,但我需要在windows上实现它。

看看这个例子o写道:

boost::mutex mut;
boost::condition_variable cond;
boost::asio::io_service io_service;
boost::asio::deadline_timer t(io_service);
void test_func()
{
    boost::mutex::scoped_lock lk(mut);
    cond.notify_all();
}
void cancel_test_func()
{
    boost::unique_lock< boost::mutex > lk(mut);
    auto canceled_timers = t.cancel();
    cond.wait(lk);
    printf("Canceled...%u.", canceled_timers);
}
int main(int argc, char* argv[])
{
  try
  {
    t.expires_from_now(boost::posix_time::seconds(5));
    t.async_wait(boost::bind(&test_func));
    io_service.post(boost::bind(cancel_test_func));
    boost::thread_group tg;
    tg.create_thread( boost::bind(&boost::asio::io_service::run, &io_service) );
    //tg.create_thread( boost::bind(&boost::asio::io_service::run, &io_service) );
    getchar();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "n";
  }
  return 0;
}

为了使这个例子起作用(取消计时器),我需要取消对第二个线程创建的注释。只有一个线程,我从来没有收到通知。问题是:这种行为正常吗?

条件变量是一个同步概念,它不能很好地与像io_service这样的事件循环集成。如果您希望在Linux上使用异步事件,请查看带有EFD_SEMAPHORE标志的eventfd(2)以了解信号量语义。我不确定在其他平台上是否有类似的接口