Created
September 28, 2023 02:30
-
-
Save EvanLyu732/7e24ed2994afdeaae4feff362bc3ee7a to your computer and use it in GitHub Desktop.
A program scenario in C++ that bind timer to a callback function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <atomic> | |
#include <iostream> | |
#include <thread> | |
#include <unistd.h> | |
// A simple timer that use atomic bool to identify it's status. | |
struct Timer { | |
bool overdue() { return flag_.load() ? true : false; } | |
void reset_timer() { | |
flag_.store(true); | |
return; | |
} | |
void reset_status() { | |
flag_.store(false); | |
return; | |
} | |
private: | |
// when flag_ is true, then timer is overdued. | |
std::atomic_bool flag_; | |
}; | |
static Timer t; | |
void trigger_callback(void (*ptr)(int)) { | |
// trigger callback for 10 timers | |
for (int i = 0; i < 10; i++) { | |
ptr(i); | |
} | |
// and not trigger callback to verify if callback monitor is on work. | |
sleep(2); | |
} | |
void callback(const int i) { | |
std::cout << "callback is triggered, reset callback monitor timer" | |
<< std::endl; | |
t.reset_status(); | |
return; | |
} | |
void callback_monitor() { | |
while (true) { | |
// check timer if is overdue | |
if (t.overdue()) { | |
std::cout << "callback is not triggered, overdue." << std::endl; | |
} | |
// | |
sleep(3); | |
t.reset_timer(); | |
} | |
} | |
int main() { | |
std::thread callback_triggered_th = std::thread(trigger_callback, &callback); | |
std::thread callback_monitor_th = std::thread(callback_monitor); | |
callback_triggered_th.join(); | |
callback_monitor_th.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment