0

需要一个运行(移动、滚动)平均算法来计算传入的 5 分钟平均位。我必须处理的是传入位的累积值。

例如:我从 0 位开始,5 分钟后,我有 10 位,所以我的平均值是 10 位。5 分钟后,我有 15 位,所以现在我的平均值是 7.5 位。又过了 5 分钟,我有 30 位,所以我现在的平均值是 10.8 位。

我的问题是,我怎样才能在 C++ 中实现一个计时器\计数器,以便它以精确的 5 分钟间隔轮询位值?显然我不能使用延迟 300 秒。但是我可以在后台制作一个定时器,它只会每 5 分钟触发一个事件(轮询位值)吗?

4

2 回答 2

1

我上一个答案的代码

#define REENTRANT
//The above is neccessary when using threads. This must be defined before any includes are made
//Often times, gcc -DREENTRANT is used instead of this, however, it produces the same effect

#include <pthread.h>

char running=1;

void* timer(void* dump){
    unsigned char i=0;
    while(running){
        for(i=0;i<300 && running;i++){
            sleep(1);//so we don't need to wait the 300 seconds when we want to quit
        }
        if(running)
           callback();//note that this is called from a different thread from main()
    }
    pthread_exit(NULL);
}

    int main(){
    pthread_t thread;
    pthread_create(&thread,NULL,timer,NULL);
    //do some stuff
    running=0;
    pthread_join(thread,NULL);//we told it to stop running, however, we might need to wait literally a second
    pthread_exit(NULL);
    return 0;
}
于 2010-03-30T14:45:30.270 回答
0

“愚蠢”的解决方案是使用 POSIX 线程。您可以创建一个线程,然后将其放入带有 sleep() 的无限循环中。

于 2010-03-25T22:42:54.513 回答