title: ways of implementing timer in worker thread in C
body: <p>I have a worker thread that gets work from pipe. Something like this</p>
  
  <pre><code>void *worker(void *param) {
    while (!work_done) {
      read(g_workfds[0], work, sizeof(work));
      do_work(work);
    }
  }
  </code></pre>
  
  <p>I need to implement a 1 second timer in the same thread do to some book-keeping about the work. Following is what I've in mind:</p>
  
  <pre><code>void *worker(void *param) {
    prev_uptime = get_uptime();
    while (!work_done) {
      // set g_workfds[0] as non-block
      now_uptime = get_uptime();
      if (now_uptime - prev_uptime &gt; 1) {
         do_book_keeping();
         prev_uptime = now_uptime;
      }
      n = poll(g_workfds[0], 1000); // Wait for 1 second else timeout
      if (n == 0) // timed out 
         continue;
      read(g_workfds[0], work, sizeof(work));
      do_work(work);   // This can take more than 1 second also
    }
  }
  </code></pre>
  
  <p>I am using system uptime instead of system time because system time can get changed while this thread is running. I was wondering if there is any other better way to do this. I don't want to consider using another thread. Using <code>alarm()</code> is not an option as it already used by another thread in same process. This is getting implemented in Linux environment. </p>