Chúng ta sẽ xem cách tạo timer dùng C++. Tạo lớp tên later. Lớp này có các thuộc tính:
- int (milliseconds chờ trước khi chạy code)
- bool (nếu true, trả về ngay lập tức, chạy code sau thời gian chỉ định trên luồng khác)
- Tham số biến đổi (variable arguments - chính xác những gì muốn truyền cho std::bind)
Có thể đổi chrono::milliseconds thành nanoseconds hoặc microseconds để thay đổi độ chính xác.
Ví dụ Code
#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);
}
Kết quả
$ g++ test.cpp -lpthread $ ./a.out result of test 2: 75 result of test 2: 101 $
Kết quả đầu tiên sau 4 giây. Kết quả thứ hai sau 3 giây từ kết quả đầu.