Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <chrono>
- struct Timer {
- std::function<void()> handler_;
- std::atomic<bool> is_running_;
- explicit Timer(std::function<void()> handler) :
- handler_(std::move(handler)), is_running_(false) {}
- void run_timer(int interval_in_seconds) {
- is_running_ = true;
- while (is_running_) {
- handler_();
- std::this_thread::sleep_for(std::chrono::seconds(interval_in_seconds));
- }
- }
- void stop_timer() {
- is_running_ = false;
- }
- };
- int main() {
- std::atomic<int> counter(0);
- Timer counter_timer([&] {
- // get current counter and increase on 1
- std::cout << "tick: " << counter.fetch_add(1) << "\n";
- });
- std::thread t = std::thread([&] {
- std::this_thread::sleep_for(std::chrono::seconds(10));
- counter_timer.stop_timer();
- });
- std::cout << "Run timer for 10 seconds\n";
- // blocking call until stop_timer is called
- counter_timer.run_timer(1);
- std::cout << "Timer finished\n";
- t.join();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement