简体   繁体   English

在C / C ++中每100毫秒重新启动计时器

[英]Have a timer restart every 100ms in C / C++

I am working with a application where the requirement is execute a function after every 100ms. 我正在使用一个要求每100毫秒执行一次功能的应用程序。 Below is my code 下面是我的代码

checkOCIDs()
{
// Do something that might take more than 100ms of time
}
void TimeOut_CallBack(int w)
{
    struct itimerval tout_val;
    int ret = 0;

    signal(SIGALRM,TimeOut_CallBack);

    /* Configure the timer to expire after 100000 ... */
    tout_val.it_value.tv_sec = 0;
    tout_val.it_value.tv_usec = 100000; /* 100000  timer */

    /* ... and every 100 msec after that. */
    tout_val.it_interval.tv_sec = 0 ;
    tout_val.it_interval.tv_usec = 100000;

    checkOCIDs();

    setitimer(ITIMER_REAL, &tout_val,0);

    return ;

}

Function TimeOut_CallBack ( ) is called only once and then on checkOCIDs( ) function must be executed after a wait of 100ms continuously. 函数TimeOut_CallBack()仅被调用一次,然后必须在连续等待100ms之后在checkOCIDs()上执行该函数。 Currently, The application is going for a block as checkOCIDs( ) function takes more than 100ms of time to complete and before that the Timer Out is triggered. 当前,由于checkOCIDs()函数需要花费超过100ms的时间来完成并且在触发Timer Out之前,该应用正在等待一个块。 I do not wish to use while(1) with sleep( ) / usleep( ) as it eats up my CPU enormously. 我不希望将while(1)与sleep()/ usleep()一起使用,因为它会极大地消耗我的CPU。 Please suggest a alternative to achieve my requirement. 请提出一种替代方案以满足我的要求。

It is not clear whether the "check" function should be executed while it is in progress and timer expires. 尚不清楚在执行过程中计时器是否到期时是否应执行“检查”功能。 Maybe it would be ok to you to introduce variable to indicate that timer expired and your function should be executed again after it completes, pseudo-code: 也许可以引入变量来指示计时器已到期,并且应该在函数完成后再次执行您的函数,伪代码:

static volatile bool check_in_progress = false;
static volatile bool timer_expired = false;

void TimeOut_CallBack(int w)
{
    // ...
    if (check_in_progress) {
        timer_expired = true;
        return;
    }

    // spawn/resume check function thread
    // ...
}

void checkThreadProc()
{
    check_in_progress = true;
    do {
        timer_expired = false;
        checkOCIDs();
    } while(timer_expired);
    check_in_progress = false;

    // end thread or wait for a signal to resume
}

Note, that additional synchronization may be required to avoid race conditions (for instance when one thread exists do-while loop and check_in_progress is still set and the other sets timer_expired, check function will not be executed), but that's depends on your requirements details. 请注意,可能需要额外的同步来避免竞争条件(例如,当一个线程存在do-while循环并且仍然设置了check_in_progress而其他设置了timer_expired时,将不执行检查功能),但这取决于您的要求详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM