এখানে আমরা দেখব কিভাবে C++ ব্যবহার করে টাইমার তৈরি করা যায়। এখানে আমরা পরে বলা একটি ক্লাস তৈরি করছি। এই শ্রেণীর নিম্নলিখিত বৈশিষ্ট্য আছে।
- int (কোড চালানো পর্যন্ত অপেক্ষা করতে মিলিসেকেন্ড)
- বুল (যদি এটি সত্য হয়, এটি অবিলম্বে ফিরে আসে এবং অন্য থ্রেডে নির্দিষ্ট সময়ের পরে কোডটি চালায়)
- ভেরিয়েবল আর্গুমেন্ট (ঠিক আমরা 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 সেকেন্ড পরে প্রথম ফলাফল। প্রথমটি থেকে তিন সেকেন্ড পরে দ্বিতীয় ফলাফল