使用boost::asio和strands的事件队列:等待新事件

Event queue using boost::asio and strands: Waiting for new events

本文关键字:新事件 事件 等待 asio boost strands 使用 事件队列      更新时间:2023-10-16

所以我想在自定义线程上用c++创建一个同步事件队列。据我所知,boost::asio::strand是一个很好的候选者,有一个转折点:当调用asio::run()时,它只在strand的队列中有事件时运行。代码:

this->control_strand_.reset(new boost::asio::strand(control_io_service_));
control_thread_ = boost::thread(boost::bind(&boost::asio::io_service::run,&control_io_service_));
control_thread_.join();

立即返回。现在我可以使用Boost Asio的答案了——如何知道处理程序队列何时为空?,但这里面有一个while循环等待。我宁愿它更基于事件(也就是说,当队列为空时,等待while look中的"wrap"调用)。我能想到的唯一方法是完全包裹strand类,让它在调用"包裹"(类似于伪代码)时触发信号

//some member variables
boost::condition_variable cond_var;
boost::mutex mut;
std::unique_ptr<boost::asio::strand> control_strand_;
boost::asio::io_service control_io_service_
//while loop,running on event processing thread
void MessageProcessor()
{
  while (true)
  {
    {
      boost::unique_lock<boost::mutex> lock(mut);
      cond_var.wait(lock);
    }
    control_io_service_.run();
  }
}
//post call,from different thread
template <typename Handler>
void wrap(Handler hand)
{
  cond_var.notify_all();
  control_strand_->wrap(hand);
}

这将在没有while循环的情况下永远运行队列(我的同步有点不正常,但这不是atm的问题)。有更好、更标准的方法吗?

您可以直接使用io_service,它实现了一个"隐式链"。要保持它的运行,只需给它一个io_service::work对象,就像在io_service引用中一样(请参阅"停止io_service耗尽工作")。

请注意,io_service是有意的线程安全的,因此您可以从外部线程为其post()函子。