Advertisement
Guest User

Untitled

a guest
Jan 20th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. #ifndef TIMER_H
  2. #define TIMER_H
  3.  
  4. #include <atomic>
  5. #include <thread>
  6. #include <chrono>
  7. #include <iostream>
  8. #include <list>
  9.  
  10. using namespace std;
  11.  
  12. class Timer {
  13. private:
  14. atomic_bool done_ {};
  15. thread worker_{};
  16. //time interval
  17. chrono::milliseconds time;
  18. void run_();
  19. Fn** fn; // function called
  20. Args** args; // Argument of this function
  21. public:
  22. template <class Fn, class... Args>
  23. Timer(chrono::milliseconds time, Fn&& fn, Args&&... args);
  24. ~Timer();
  25. };
  26.  
  27. #endif // TIMER_H
  28.  
  29. #include "timer.h"
  30.  
  31. template <class Fn, class... Args>
  32. Timer::Timer(chrono::milliseconds time,Fn&& fn, Args&&... args){
  33. this->time = time;
  34. this->fn = fn;
  35. this->args = args;
  36. worker_ = thread(&Timer::run_,this);
  37. }
  38. // Thread method
  39. void Timer::run_(){
  40. while(!this->done_.load()){
  41. //call function
  42. this_thread::sleep_for(time);
  43. }
  44. }
  45.  
  46. Timer::~Timer(){
  47. done_.store(true);
  48. if(worker_.joinable())
  49. worker_.join();
  50. else
  51. cout << "thread termined" << endl;
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement