I want to implement some system in c++ so that I can call a function and ask for another function to be called in X milliseconds. Something like this:
callfu
Do you want it to by asynchronous so that the callback gets executed when 25 miliseconds are over without blocking the main executing thread? If so, you can execute the callback in a separate thread from the timer / timed callback function you implement.
If you do not use multithreading, then your main or the calling function of callfunctiontimed(25, funcName); would block while you run a sleep / usleep. It is your choice now as to what behavior you want to implement.
The real solution would not be as simple as to multithread or not. There are things like, how do you keep different timers/callbacks information considering the function can be called multiple times with different timeouts and functions.
One way to do it, would be like this:
As the timer thread is done sleeping, it removes and looks at head of the list and executes the function pointer in a new thread. Timer thread is re-initialized with sleep time on the new head of the list.
main() {
//spawn a timer thread with pthread create
callfunctiontimed(25, test);
callfunctiontimed(35, show);
callfunctiontimed(4, print);
}
callfunctionTImed(int time, (func*)function, void*data) //
{
//add information to sorted list of timer and callbacks
//re-initialize sleep_time for timer thread if needed.
return.
}
timerThread() {
while(1){
sleep(sleep_time);
//look at head of timer list, remove it, call function in a new thread
//adjust sleep time as per new head
}
}
Hopefully this gives an idea of what I meant, although this is not perfect and has several problems.