C++ 在1个线程上运行的boost::asio::io_服务如何在等待条件下唤醒
谢谢你回复Sam Miller,但我需要在windows上实现它 看看这个例子,o写道:C++ 在1个线程上运行的boost::asio::io_服务如何在等待条件下唤醒,c++,boost,boost-asio,C++,Boost,Boost Asio,谢谢你回复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
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;
}
boost::mutexmut;
boost::条件变量cond;
boost::asio::io_服务io_服务;
boost::asio::截止时间计时器t(io\u服务);
无效测试_func()
{
boost::mutex::作用域锁定lk(mut);
条件通知所有人();
}
作废取消测试功能()
{
boost::unique_locklk(mut);
自动取消定时器=t.取消();
条件等待(lk);
printf(“取消…%u.”,取消计时器);
}
int main(int argc,char*argv[])
{
尝试
{
t、 从现在起过期(boost::posix_time::seconds(5));
t、 异步等待(boost::bind(&test_func));
io_service.post(boost::bind(cancel_test_func));
boost::线程组tg;
创建线程(boost::bind(&boost::asio::io_服务::run,&io_服务));
//创建线程(boost::bind(&boost::asio::io_服务::run,&io_服务));
getchar();
}
捕获(标准::异常&e)
{
std::cerr条件变量是一个同步概念,它不能很好地与事件循环(如io_服务)集成。如果您想在Linux上使用异步事件,请查看带有EFD_信号量的信号量语义标志。我不确定在其他平台上是否有类似的接口n锁定互斥锁,io\u服务
线程由于timer.cancel()
而进入timeout\u func
,并通知在“main”中等待的cond
线程-没有无限的等待。但是同一个线程怎么能进入timeout\u func
并等待条件呢?要进入timeout\u func
它应该中断等待,转到callback,调用notify\u one
然后返回到条件的wait
它不是同一个线程,这是两个不同的线程:线程集启动计时器,创建线程B并传递给它io_服务::run
函数,然后立即取消计时器,并等待cond
。作为计时器取消的结果,线程B调用完成处理程序,即输入timeout_函数
,并通知cond
。现在我明白了,我的示例适用于beca使用我有两个线程,一个是主线程,另一个是。无论如何,我刚刚意识到当我们使用boost的io_服务时,总是至少有两个线程,一个是主线程,另一个是使io_服务::运行的线程。好的,谢谢。当然,您可以在下面的行中创建一个附加线程:boost::thread t(boost::bind(&boost::asio::io服务::run,&io));
。io_service::run是否必须有单独的线程是一个设计问题。请参阅第一个Asio示例,它没有额外的线程: