猜想:使用make_work_guard有可能是让io一直保活,不被当没有任务的时候,一直轮询,除非自己调用stop函数。欢迎大家留言,这只是我的猜想.
#include<iostream>
#include<boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <thread>
void print(const boost::system::error_code& e);
boost::asio::io_context ios;
boost::asio::steady_timer heart_timer_(ios);
void print(const boost::system::error_code& ec)
{
if (ec){
return;
}
std::cout << "Hello!"<<std::endl;
heart_timer_.expires_from_now(std::chrono::seconds(10));
heart_timer_.async_wait(std::bind(print, std::placeholders::_1));
}
int main()
{
int count = 1;
//heart_timer_.expires_at(std::chrono::steady_clock::now() + std::chrono::seconds(30));
heart_timer_.async_wait(std::bind(print,std::placeholders::_1));
auto work_(boost::asio::make_work_guard(ios));
std::thread t([&]() {
boost::system::error_code ec;
ios.run(ec);
});
while (1) {
if (count ==10){
ios.stop();
}
++count;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}