यहां हम देखेंगे कि C++ का उपयोग करके टाइमर कैसे बनाया जाता है। यहां हम एक वर्ग बना रहे हैं जिसे बाद में कहा जाता है। इस वर्ग में निम्नलिखित गुण हैं।
- int (कोड चलाने तक प्रतीक्षा करने के लिए मिलीसेकंड)
- बूल (यदि यह सत्य है, तो यह तुरंत वापस आ जाता है, और निर्दिष्ट समय के बाद कोड को किसी अन्य थ्रेड पर चलाता है)
- परिवर्तनीय तर्क (बिल्कुल हम std::bind को खिलाना चाहते हैं)
सटीकता को बदलने के लिए हम क्रोनो ::मिलीसेकंड को नैनोसेकंड या माइक्रोसेकंड आदि में बदल सकते हैं।
उदाहरण कोड
#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 सेकंड के बाद पहला परिणाम। पहले वाले से तीन सेकंड के बाद दूसरा परिणाम