Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef TIMER_H
- #define TIMER_H
- #include <atomic>
- #include <thread>
- #include <chrono>
- #include <iostream>
- #include <list>
- using namespace std;
- class Timer {
- private:
- atomic_bool done_ {};
- thread worker_{};
- //time interval
- chrono::milliseconds time;
- void run_();
- Fn** fn; // function called
- Args** args; // Argument of this function
- public:
- template <class Fn, class... Args>
- Timer(chrono::milliseconds time, Fn&& fn, Args&&... args);
- ~Timer();
- };
- #endif // TIMER_H
- #include "timer.h"
- template <class Fn, class... Args>
- Timer::Timer(chrono::milliseconds time,Fn&& fn, Args&&... args){
- this->time = time;
- this->fn = fn;
- this->args = args;
- worker_ = thread(&Timer::run_,this);
- }
- // Thread method
- void Timer::run_(){
- while(!this->done_.load()){
- //call function
- this_thread::sleep_for(time);
- }
- }
- Timer::~Timer(){
- done_.store(true);
- if(worker_.joinable())
- worker_.join();
- else
- cout << "thread termined" << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement