Guest User

Untitled

a guest
Dec 13th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. #include <thread>
  2. #include <chrono>
  3. #include <functional>
  4. #include <iostream>
  5.  
  6. template<typename I>
  7. class StatisticMonitor {
  8. public:
  9. typedef std::function<I()> Watcher;
  10.  
  11. StatisticMonitor &watch(Watcher tput) {
  12. this->current_value = tput;
  13. return *this;
  14. }
  15.  
  16. StatisticMonitor &set_name(std::string name) {
  17. this->name = std::move(name);
  18. return *this;
  19. }
  20.  
  21. void launch() {
  22. if (timer != nullptr) {
  23. return;
  24. }
  25. timer = new std::thread([=]() {
  26. while (non_terminated) {
  27. std::cout << name << ": " << current_value() << std::endl;
  28. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  29. }
  30. std::cout << name << " now terminates. " << endl;
  31. });
  32. }
  33.  
  34. void terminate() {
  35. if (timer != nullptr) {
  36. non_terminated = false;
  37. timer->join();
  38. delete timer;
  39. timer = nullptr;
  40. }
  41. }
  42.  
  43. private:
  44. bool non_terminated = true;
  45. std::thread *timer = nullptr;
  46. std::string name;
  47. Watcher current_value;
  48. };
Add Comment
Please, Sign In to add comment