如何使用 C++11 建立計時器?


我們將在此處看到如何使用 C++ 製作計時器。我們在此建立一個類,稱為 later。此類具有以下屬性。

  • int(在執行程式碼之前等待的毫秒數)
  • bool(如果此項為真,則會立即返回,並在另一執行緒中在指定時間後執行程式碼)
  • 變數引數(我們確實希望饋送至 std::bind)

我們可以將 chrono::milliseconds 更改為納秒或微秒等以更改精度。

示例程式碼

#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 秒後顯示第 1 個結果。3 秒後顯示第 2 個結果

更新於:2019-07-30

1K+ 觀看

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告