如何实现一个计时器中断C ++? [英] How to implement a timer with interruption in C++?

查看:242
本文介绍了如何实现一个计时器中断C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GCC编译器和C ++,我想要一个计时器,当倒计时为0时触发中断。



任何想法?提前感谢。



编辑



感谢Adam,做它。



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



实际上,这些计时器是非常基本的。在NCURSES,我有一个事情的列表。当我按下一个键,其中的一件事会改变颜色5秒。如果我按另一个键,列表中的另一件事情将会做同样的事情。这就像强调字符串取决于用户输入。

解决方案

一种方法是使用 alarm(2) 系统调用发送 SIGALRM 到定时器运行时的进程:

  void sigalrm_handler b $ b {
//当定时器用完时调用。尽量不要在这里做太多;
//建议的做法是设置一个标志(类型为sig_atomic_t),并有
//代码在其他地方检查该标志(例如在程序的主循环中)
}

...

signal(SIGALRM,& sigalrm_handler); //设置信号处理程序
alarm(10); //从现在起设置一个警报10秒钟

小心注意手册页闹钟


闹钟> setitimer()共享相同的计时器;

sleep()可以使用 SIGALRM 来实现;

混合调用 alarm() sleep()是一个坏主意。



,使得处理的执行被延迟任意时间量。



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 about 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?

解决方案

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.

这篇关于如何实现一个计时器中断C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆