提升截止时间计时器我的代码不能同时运行

时间:2015-11-11 07:35:33

标签: c++ timer

我打算在我的项目中使用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;
}

2 个答案:

答案 0 :(得分:1)

io_service.run()的提升文档说:

  

run()函数会阻塞,直到所有工作完成,并且不再有调度程序,或者直到io_service停止。

因此,正如预期的那样,调用它将等到计时器到期,此时不再需要调用工作并且run()返回。这个想法是你应该将你的其他功能放到boost处理程序中,以便可以通过boost的IO系统调用它们,而run()取代你自己的主循环。

另一种选择是投票。对于您的示例,您需要在循环之前删除io.run()调用,并在循环中调用io.poll()。 (请注意,还有version of poll()可以返回有关错误的信息。)

如果你这样做,你还需要想出一种让你的主循环停止执行的方法;只需将io.poll()调用到您的循环中即可获得您期望的输出,但您仍处于无限循环中。

答案 1 :(得分:1)

问题是你的io.run()阻止,只要有工作要做,在这种情况下,直到你的计时器到期。对于这个特定的例子,你可以通过使用标准的C ++ 11库函数实现你正在尝试的东西,更容易IMHO,例如

#include <iostream>
#include <chrono>
#include <future>

using namespace std;

int main()
{
  auto handle = std::async(
      // set this to force execution on separate thread
      std::launch::async, 
      // a simple lambda to sleep for 1 second and print smth
      []() {
        std::this_thread::sleep_for (std::chrono::seconds(1));
        std::cout<<"timer expired..." << endl;
      });

  std::cout << "Running" << std::endl;
  while (1) {
    std::cout<<"Main execution..." << endl;
    std::this_thread::sleep_for (std::chrono::seconds(5));                                                                                                                       
  }
  return 0;
}

编译并运行:

→ g++ -std=c++11 test.cpp -pthread && ./a.out
Running
Main execution...
timer expired...
Main execution...
^C

这是否适用于您的其他应用程序我无法从您的帖子中了解到,但是自C ++ 11以来标准线程/异步功能已经有了显着改进,值得尝试一下:)