开发者

How to implement a timer with interruption in C++?

开发者 https://www.devze.com 2023-01-22 03:31 出处:网络
I\'m using the GCC compiler and C++ and I want to make a timer that triggers an interruption when the countdown is 0.

I'm using the GCC compiler and C++ and I want to make a timer that triggers an interruption when the countdown is 0.

Any Ideas? Thanks in advance.

EDIT

Thanks to Adam, I know how to do it.

Now. What abou开发者_如何学Pythont multiple timers running in parallel?

Actually, these timers are for something very basic. In NCURSES, I have a list of things. When I press a key, one of the things will change colors for 5 seconds. If I press another key, another thing in the list will do the same. It's like emphasize strings depending on the user input. Is there a simpler way to do that?


An easy, portable way to implement an interrupt timer is using Boost.ASIO. Specifically, the boost::asio::deadline_timer class allows you to specify a time duration and an interrupt handler which will be executed asynchronously when the timer runs out.

See here for a quick tutorial and demonstration.


One way to do it is to use the alarm(2) system call to send a SIGALRM to your process when the timer runs out:

void sigalrm_handler(int sig)
{
    // This gets called when the timer runs out.  Try not to do too much here;
    // the recommended practice is to set a flag (of type sig_atomic_t), and have
    // code elsewhere check that flag (e.g. in the main loop of your program)
}

...

signal(SIGALRM, &sigalrm_handler);  // set a signal handler
alarm(10);  // set an alarm for 10 seconds from now

Take careful note of the cautions in the man page of alarm:

alarm() and setitimer() share the same timer; calls to one will interfere with use of the other.

sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.

Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time.

0

精彩评论

暂无评论...
验证码 换一张
取 消