How to create timer events using C++ 11?

前端 未结 5 1084
执念已碎
执念已碎 2020-11-27 02:24

How to create timer events using C++ 11?

I need something like: “Call me after 1 second from now”.

Is there any library?

5条回答
  •  感动是毒
    2020-11-27 03:06

    The asynchronous solution from Edward:

    • create new thread
    • sleep in that thread
    • do the task in that thread

    is simple and might just work for you.

    I would also like to give a more advanced version which has these advantages:

    • no thread startup overhead
    • only a single extra thread per process required to handle all timed tasks

    This might be in particular useful in large software projects where you have many task executed repetitively in your process and you care about resource usage (threads) and also startup overhead.

    Idea: Have one service thread which processes all registered timed tasks. Use boost io_service for that.

    Code similar to: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html

    #include 
    #include 
    #include 
    
    int main()
    {
      boost::asio::io_service io;
    
      boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
      t.async_wait([](const boost::system::error_code& /*e*/){
        printf("Printed after 1s\n"); });
    
      boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
      t2.async_wait([](const boost::system::error_code& /*e*/){
        printf("Printed after 1s\n"); });
    
      // both prints happen at the same time,
      // but only a single thread is used to handle both timed tasks
      // - namely the main thread calling io.run();
    
      io.run();
    
      return 0;
    }
    

提交回复
热议问题