是否可以将处理程序附加到系统计时器上?
Is it possible to attach handler to a system timer?
我想为以下事件注册处理程序:"系统时钟计时器增加第二计数器"。是否可以为此事件附加处理程序?换句话说,我想每秒调用一个合适的函数。看来下面的解决方案很糟糕:
#include <ctime>
bool checkTimer(int sec_now)
{
time_t t= time(0);
int sec=localtime(&t)->tm_sec;
if(sec_now!=sec)
return true;
return false;
}
void callback()
{
//handler
}
int main()
{
while(true)
{
time_t t= time(0);
int sec_now=localtime(&t)->tm_sec;
while(!checkTimer(sec_now)){ }
callback();
}
}
这段代码按我想要的方式工作。但我认为这是不好的方式。你能提出另一种方法吗?我用的是linux mint 14
这段代码按我想要的方式工作。但我认为这是不好的方式。
这个实现的问题是程序在忙循环:它在一个核心上消耗了所有的CPU时间。有几种方法可以在Linux上实现间隔计时器。例如,您可以查看timerfd。
#include <iostream>
#include <inttypes.h>
#include <sys/timerfd.h>
#include <unistd.h>
void callback(void)
{
std::cout << "callback()" << std::endl;
}
int main(void)
{
int tfd;
uint64_t count;
// Interval timer that expires every 1 second
struct itimerspec timer = {
.it_interval = {1, 0}, // interval for periodic timer
.it_value = {1, 0}, // initial expiration
};
tfd = timerfd_create(CLOCK_MONOTONIC, 0);
timerfd_settime(tfd, 0, &timer, NULL);
while (true) {
read(tfd, &count, sizeof(count));
callback();
}
close(tfd);
return 0;
}
相关文章:
- Linux的Cpp上的计时器
- 提升 ASIO 无法识别计时器对象
- 提升 asio 并发计时器取消问题与链
- 使用单体计时器的pthread_cond_timedwait有时会比预期晚超时
- 窗口中的微秒计时器
- 计时器是否从另一个线程启动?
- 如何在 c++ 中创建计时器
- C++回调计时器实现
- 在计时器或主线程外部的命令上销毁/替换线程
- 如何制作每秒从 30 乘 1 倒计时的计时器?
- 保留计时器集合(对象与指针)的最佳方法
- 在网络套接字计时器滴答后增加asio短读错误
- 是否可以仅使用标准 c++/c++11 实现不带"sleep"的计时器?
- 在没有NtSetTimerResolution的Windows上提高计时器分辨率(高分辨率)
- 计时器坏了或者其他什么的
- 功能计时器阻止主功能继续
- IO服务重新启动后,Boost最后期限计时器持续触发
- 如何获取当前的 Windows 系统范围的计时器分辨率
- 如何在c++中使用boost实现与系统时间无关的计时器回调
- 是否可以将处理程序附加到系统计时器上?