如何在 C++ 中实现带有中断的计时器?

2021-12-31 00:00:00 gcc timer c++ interrupt

我正在使用 GCC 编译器和 C++,我想制作一个计时器,当倒计时为 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.

编辑

感谢 Adam,我知道该怎么做.

Thanks to Adam, I know how to do it.

现在.多个计时器并行运行怎么样?

Now. What about multiple timers running in parallel?

实际上,这些计时器用于非常基本的事情.在 NCURSES 中,我有一个清单.当我按下一个键时,其中一个会改变颜色 5 秒钟.如果我按下另一个键,列表中的另一件事也会做同样的事情.这就像根据用户输入强调字符串.有没有更简单的方法来做到这一点?

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?

推荐答案

一种方法是使用 alarm(2) 系统调用,用于在计时器用完时向您的进程发送 SIGALRM:

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

注意alarm手册页中的注意事项:

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

alarm() 和 setitimer() 共享同一个计时器;调用一个会干扰另一个的使用.

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

sleep() 可以使用 SIGALRM 实现;混合调用 alarm() 和 sleep() 是个坏主意.

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.

相关文章