简体   繁体   中英

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. 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. 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. I do not wish to use while(1) with sleep( ) / usleep( ) as it eats up my CPU enormously. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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