我计划在我的项目中使用 boost c++ 库来满足我的一次性计时器要求。
在我的程序中,计时器已启动,我希望我的程序在计时器运行时继续执行,但在下面的代码中,我的程序被阻止了 直到计时器到期.. 有没有办法做到这一点。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& /*e*/)
{
std::cout<<"timer expired...";
}
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t1(io, boost::posix_time::seconds(5));
t1.async_wait(print);
io.run();
int var;
while(1) { // i want this loop to execute while timer running....
std::cout<<"Main execution...\n";
std::cin>>var;
}
return 0;
}
最佳答案
io_service.run() 的提升文档说:
The run() function blocks until all work has finished and there are no more handlers to be dispatched, or until the io_service has been stopped.
因此,正如预期的那样,调用它会等到计时器到期,此时没有更多的工作可以调用并且 run()
返回。这个想法是,您应该将其他函数放入 boost 处理程序中,以便它们可以被 boost 的 IO 系统调用,并且 run()
取代您自己的主循环。
另一种方法是轮询。对于您的示例,您可能希望从循环之前删除 io.run()
调用,然后调用 io.poll()在你的循环中。 (请注意,还有一个 version of poll() 可以返回有关错误的信息。)
如果你这样做,你还需要想出一种方法让你的主循环停止执行;只需将对 io.poll()
的调用放入您的循环中就可以得到您期望的输出,但您仍然处于无限循环中。
关于c++ - 提升截止时间计时器我的代码没有同时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646040/