title: What is the best way to get tight timing of a thread in c (pthreads)
body: <p>Ok so I have a thread that I need to run exactly every 10ms, but it takes a variable amount of processing time (for simplicity we can assume the processing time is less than 10ms). Small deviations in the timing will, over time, add up and become a problem. </p>
  
  <p>This is my current solution. It seems clunky, but moreso I'm worried about the time it takes to run timeval_subtract causing my timing to be off.  Does anyone have a better solution?</p>
  
  <p>This is for a library and I cannot use system resources like timers or clocks.</p>
  
  <pre><code>void mythread(void *ptr )
  {
      struct timeval tv_being, tv_end;
      int usToSleep;
  
      while(1)
      {
          gettimeofday(&amp;tv_begin)
  
          //do stuff
  
          //now determine how long to sleep so we wake up 10ms after previous wakeup
  
          gettimeofday(&amp;tv_end)
  
          usToSleep = timeval_subtract(tv_begin, tv_end); //this will return 10ms minus the elapsed time
  
          usleep(usToSleep);
      }
  
      return;
  }
  </code></pre>