如何使用 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 个结果
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP