是否可以将处理程序附加到系统计时器上?

Is it possible to attach handler to a system timer?

本文关键字:系统 计时器 处理 程序 是否      更新时间:2023-10-16

我想为以下事件注册处理程序:"系统时钟计时器增加第二计数器"。是否可以为此事件附加处理程序?换句话说,我想每秒调用一个合适的函数。看来下面的解决方案很糟糕:

#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;
}