我有一个如下的测试程序:
io_service io;
deadline_timer t1(io);
deadline_timer t2(io);
t1.expires_from_now(boost::posix_time::seconds(10));
t1.async_wait([](const boost::system::error_code &error) {
if (error == boost::asio::error::operation_aborted) {
cout << "timer1 canceled" << endl;
} else {
cout << "timer1 expired" << endl;
}
});
t2.expires_from_now(boost::posix_time::seconds(2));
t2.async_wait([&t1](const boost::system::error_code &error) {
if (error == boost::asio::error::operation_aborted) {
cout << "timer2 canceled" << endl;
} else {
t1.cancel();
for (int i = 0; i < 5000000; i++) {
cout << i << endl;
}
# usleep(1000000);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
cout << "timer2 expired" << endl;
}
});
io.run();
我想知道timer2何时到期并取消timer1,“ timer1已取消”和“ timer2已到期”中的哪一个将首先打印?
结果为“ timer2已过期”。这是有道理的,因为单线程程序将执行直到出现一些“块”。
但是,在插入“ sleep_for(1000ms)”行(这会阻止执行,将过程转换为“ Sleep”)之后,仍然在“ timer1 canceled”行之前打印“ timer2 expired”行。
在我的想象中,boost:asio是围绕“ epoll”编写的内容,它可以处理“事件”(例如来自网络的传入消息,timer2到期)和“块”(例如,将数据写入磁盘)(睡眠)单线程。但是,为什么在“ sleep_for”之后没有显示“ timer1 canceled”行?
问题2:假设一个程序在一个线程中处理网络请求和Chrono作业。
void fun1(){
timer1.expire_from_now(3s);
timer1.async_wait([](const & error){
cout<<"timer1 expired";
heavy_job();
});
}
fun1到期,并执行cout<<"timer1 expired"
,但未执行。沉重的工作呢。此时,来自网络的请求触发了fun2:
int wait_funcs= timer1.expire_from_now(3s);
if (wait_funcs == 0 ){
job2();
}else{
job3();
}
以下哪种情况会发生?
-
完成繁重工作-> job2: 这意味着func1不会被fun2打断,fun2将在fun1完成(或阻止?)后运行。
-
job2完成-> heavy_job: 这意味着wait_funcs检查检测到不安全行为
对不起我的示范,我是新来的boost:asio,很困惑。