Advertisement
NLinker

Passing functions to methods

Feb 18th, 2020
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4.  
  5. struct Timer {
  6.     std::function<void()> handler_;
  7.     std::atomic<bool> is_running_;
  8.  
  9.     explicit Timer(std::function<void()> handler) :
  10.             handler_(std::move(handler)), is_running_(false) {}
  11.  
  12.     void run_timer(int interval_in_seconds) {
  13.         is_running_ = true;
  14.         while (is_running_) {
  15.             handler_();
  16.             std::this_thread::sleep_for(std::chrono::seconds(interval_in_seconds));
  17.         }
  18.     }
  19.  
  20.     void stop_timer() {
  21.         is_running_ = false;
  22.     }
  23. };
  24.  
  25. int main() {
  26.     std::atomic<int> counter(0);
  27.  
  28.     Timer counter_timer([&] {
  29.         // get current counter and increase on 1
  30.         std::cout << "tick: " << counter.fetch_add(1) << "\n";
  31.     });
  32.  
  33.     std::thread t = std::thread([&] {
  34.         std::this_thread::sleep_for(std::chrono::seconds(10));
  35.         counter_timer.stop_timer();
  36.     });
  37.  
  38.     std::cout << "Run timer for 10 seconds\n";
  39.     // blocking call until stop_timer is called
  40.     counter_timer.run_timer(1);
  41.     std::cout << "Timer finished\n";
  42.  
  43.     t.join();
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement