I'm facing a rather basic problem that I'd like to implement in C++(11 is Ok) using only standard libs.
Assume a function "Message()" which can be called any given number of times, after it's not called for a given time I want to trigger an action. For example:
Message();
Message();
Message();
Message();
sleep(10); <-- the idle time triggers an action
Message();
Hope this makes sense.
The way I implemented this so far is using a combination of an async while loop and a condition variable which I pulse every time a message comes in. Once the wait for the CV times out I take action.
In pseudo-code:
void Message(){
unique_lock ul(M);
new message = false;
CV.notify();
}
...
future = std::async([]{
do {
unique_lock ul(M);
new message = false;
got_message_within_time = CV.wait_for(ul, 20ms, new_message==true);
} while got_message_within_time;
// Got a timeout here...
time_to_take_action();
});
...
Message()
Message()
Message()
sleep(10)
I'm not convinced this is the most elegant solution out there, anyone has better suggestions? All in all the fundamental statement I want to implement is: "once I stop calling you, do something"
Any help/suggestion is welcome
Thanks !
Aucun commentaire:
Enregistrer un commentaire