如何使用C ++ 11创建计时器?

在这里,我们将看到如何使用C ++制作计时器。在这里,我们将创建一个稍后称为的类。此类具有以下属性。

  • int(等待运行代码的毫秒数)

  • bool(如果为true,则立即返回,并在指定时间后在另一个线程上运行代码)

  • 可变参数(正是我们想提供给std::bind)

我们可以将chrono ::毫秒更改为纳秒或微秒等,以更改精度。

范例程式码

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later {
   public:
      template <class callable, class... arguments>
      later(int after, bool async, callable&& f, arguments&&... args){
      std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
      if (async) {
         std::thread([after, task]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
         }).detach();
      } else {
         std::this_thread::sleep_for(std::chrono::milliseconds(after));
         task();
      }
   }
};
void test1(void) {
   return;
}
void test2(int a) {
   printf("result of test 2: %d\n", a);
   return;
}
int main() {
   later later_test1(3000, false, &test1);
   later later_test2(1000, false, &test2, 75);
   later later_test3(3000, false, &test2, 101);
}

输出结果

$ g++ test.cpp -lpthread
$ ./a.out
result of test 2: 75
result of test 2: 101
$

4秒后的第一个结果。从第一个开始三秒钟后的第二个结果