/**
* @brief 测试定时器同步调用
*/
#include
#include
#include
#include
using namespace boost;
int main()
{
asio::io_service io;
asio::steady_timer timer(io, std::chrono::seconds(3));
timer.wait();
std::cout << "Hello, world!" << std::endl;
return 0;
}
/**
* @brief 测试定时器异步调用
*/
#include
#include
#include
#include
#include
#include
#include
using namespace boost;
asio::io_service *g_io = nullptr;
void Print(const system::error_code &ec, asio::steady_timer *timer, int *count)
{
if (ec)
return;
if (*count < 3)
{
std::cout << "Count: " << *count << std::endl;
++(*count);
timer->expires_from_now(std::chrono::milliseconds(1000));
// timer->expires_at(timer->expires_at() + std::chrono::seconds(1)));
timer->aysnc_wait(boost::bind(&Print, boost::asio::placeholders::error, timer, count));
}
else
{
g_io->stop();
}
}
int DoProcess(asio::steady_timer *timer, int* count)
{
sleep(1);
timer->aysnc_wait(boost::bind(&Print, boost::asio::placeholders::error, timer, count));
sleep(8);
return 0;
}
int main(int argc, char * argv[])
{
int count = 0;
asio::io_service io;
asio::io_service::work work(io);
asio::steady_timer timer(io, std::chrono::seconds(3));
g_io = &io;
// 这里使用指针传递 可以使用std::ref(count)传递引用
std::thread t(DoProcess, &timer, &count);
std::cout << "run before..." << std::endl;
io.run();
std::cout << "run after..." << std::endl;
if (t.joinable())
t.join();
return 0;
}
由于io_service并不会主动创建调度线程,需要我们手动分配,常见的方式是给其分配一个线程,然后执行run函数。但run函数在io事件完成后会退出,线程会终止,后续基于该对象的异步io任务无法得到调度。
解决这个问题的方法是通过一个boost::asio::io_service::work对象来守护io_service。这样,即使所有io任务都执行完成,也不会退出,继续等待新的io任务。
boost::asio::io_service io;
boost::asio::io_service::work work(io);
io.run();
deadline_timer的用法参考:
https://blog.csdn.net/Erice_s/article/details/129965005