Non-blocking timer, waiting 20 seconds before starting another timer
I want to turn on the timer 20 seconds after the start of the stream. How can I do this without blocking execution.
So my thread input function is ThreadInAction. I want to wait 20 seconds before starting the timer from ThreadInAction, but I don't want to block this thread using sleep or whatever. How do we do it?
void* ThreadInAction()
{
//code
}
source to share
this little example should be portable enough.
Of course, in a real application, you would like to do something smarter than just print a message, and the main body of the thread would want to continue (although perhaps polling an event so it knows when the timer is off).
Note that signal handlers are only called at specific points in your code. Generally, you can assume that they will interrupt system calls (in this case, the base call is nanosleep()
in std::this_thread::sleep_for
. However, to avoid surprises, it's worth checking the documentation.
For an even more complex system with multiple high (ish) -resolution timers, there is a call setitimer
exported fromsys/time.h
Some links below:
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <thread>
using namespace std;
void alarm_handler(int i)
{
cout << "alarm signalled " << i << endl;
}
int main()
{
struct sigaction alarm_action;
memset(&alarm_action, sizeof(alarm_action), 0);
alarm_action.sa_handler = &alarm_handler;
alarm_action.sa_flags = 0;
alarm_action.sa_mask = 0;
sigaction(SIGALRM, &alarm_action, nullptr);
alarm(2);
cout << "waiting " << endl;
auto t0 = chrono::high_resolution_clock::now();
this_thread::sleep_for(chrono::seconds(10));
auto t1 = chrono::high_resolution_clock::now();
auto diff = chrono::duration_cast<chrono::milliseconds>(t1-t0);
cout << "signalled after " << diff.count() << " milliseconds" << endl;
return 0;
}
control the action to be taken when the timer is signaled: http://man7.org/linux/man-pages/man2/sigaction.2.html
using a timer chain: http://linux.die.net/man/2/setitimer
simple alarm with scheduled alarm call: http://linux.die.net/man/2/alarm
source to share
Your function should be doing something during this 20 second period or sleeping. If you don't want him to sleep, you can poll the time in a loop until 20 seconds have passed.
For example: In the following code, suppose it getTime()
returns the current time in milliseconds (this could be the time since your computer was started or since a specific date and time).
#define TWENTY_SECONDS_PERIOD 20000
void* ThreadInAction()
{
int initTime = getTime();
while((getTime() - initTime) < TWENTY_SECONDS_PERIOD)
{
//do nothing
}
//your code
}
Equivalent getTime()
is some API provided by your OS, library or standard library.
source to share