user3810155
user3810155

Reputation:

How to do repeated timed-callback in standard C++?

How can I do repeated timed-callback in standard C++?

I've done this in C by using SDL_AddTimer, which calls a Uint32 (*callback)(Uint32, void*) after its first argument in milliseconds has passed, get the return value to wait for that moment and call again, and repeat this until either the return value is 0 or SDL_RemoveTimer was called.

I think I can wrap this using variadic templates, or even implement it with a linked list of threads, but I'd prefer a standard library solution if there is one. I was looking at std::future and its related classes, but I'm still not clear how they are used.

A very simple piece of code would help very much.

Upvotes: 2

Views: 1940

Answers (1)

Christophe
Christophe

Reputation: 73446

A possible alternative would be to use standard threads.

The raw idea would be something like:

#include <thread>
#include <chrono>
#include <atomic>

std::atomic<bool> active; 

void mytimethread ()   // function that's executed in a separate thread
{
    active = true; 
    while (active) {
       do_callback();     // you coud also use a function pointer if you prefer
       std::this_thread::sleep_for (std::chrono::minutes(1));   // wait 1 minute
       }  
}

To activate your timer, you would then instantiate a thread:

thread t1 (mytimethread);  // create an launch thread 

... // do your stuff 

active = false;    // when you've finished you must tell the thread  
t1.join ();        // and wait that it returns 

Of course, it's just ther raw idea. I'd suggest to wrap all this into a nice self-contained class.

You shall be aware of a small limitation of sleep_for(): multi-threading management operations may cause certain delays beyond the requested duration. For most applications it will perfectly do the job, but if i'ts a risk for you, you'll be bound to system specific timers such as signal(SIGALRM, ...)/alarm() on linux or SetWaitableTimer() / SetTimer() on windows.

Upvotes: 1

Related Questions