Search code examples
cpthreadsposix

Execute a task cyclic using posix threads


I'm searching for a solution to start a method every 20ms. I found some solutions for c++ but am still searching for a solution in c which uses posix threads. I dont want to execute the method and wait for n milliseconds as this will take 20ms + X. I really want to start every 20 ms.. does someone has any idea?


Solution

  • The clock_nanosleep() POSIX function has an absolute deadline mode:

    #define NSEC_PER_SEC 1000000000
    /* Initial delay, 7.5ms */
    const long start_delay_ns = 7500000;
    /* Cycle time, 20ms */
    const long cycle_time_ns = 20000000;
    struct timespec deadline;
    
    clock_gettime(CLOCK_MONOTONIC, &deadline);
    deadline.tv_nsec += start_delay_ns;
    deadline.tv_sec += deadline.tv_nsec / NSEC_PER_SEC;
    deadline.tv_nsec %= NSEC_PER_SEC;
    
    for (;;)
    {
        struct timespec now;
    
        /* Sleep until deadline */
        while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &deadline, NULL) != 0)
            if (errno != EINTR)
                return; /* error handling here */
    
        cyclic_function(arguments);    /* Your cyclic function */
    
        /* Calculate next deadline */
        deadline.tv_nsec += cycle_time_ns;
        deadline.tv_sec += deadline.tv_nsec / NSEC_PER_SEC;
        deadline.tv_nsec %= NSEC_PER_SEC;
    
        clock_gettime(CLOCK_MONOTONIC, &now);
        if (now.tv_sec > deadline.tv_sec || (now.tv_sec == deadline.tv_sec && deadline.tv_nsec > now.tv_nsec))
            return; /* time overrun error handling here */
    }