title: Sleeping in a Thread (C / POSIX Threads)
body: <p>I am developing a multithreaded application that makes use of <a href="http://en.wikipedia.org/wiki/POSIX_Threads" rel="noreferrer">POSIX Threads</a>. I am using threads for doing a <strong>periodical</strong> job and for that purpose I am using <a href="http://linux.die.net/man/3/usleep" rel="noreferrer">usleep(3)</a> to suspend thread execution. My question is how can I cancel usleep() timer from the main thread, I tried <code>pthread_kill(thread, SIGALRM)</code> but it has a global effect which results in termination of the main application (by default). Here is my pseudo code:</p>
  
  <pre><code>void threaded_task(void *ptr) {
      initialize();
  
      while(running) {
          do_the_work();
          usleep(some_interval);
      }
  
      clean_up();
      release_resources();
  }
  </code></pre>
  
  <p>And here is the pseudo function that is used to stop (and <strong>gracefully shutdown</strong>) given thread from the <strong>main thread</strong>:</p>
  
  <pre><code>void stop_thread(pthread_t thread) {
      set_running_state(thread, 0); // Actually I use mutex staff
      // TODO: Cancel sleep timer so that I will not wait for nothing.
      // Wait for task to finish possibly running work and clean up 
      pthread_join(thread, NULL);
  }
  </code></pre>
  
  <p>What is the convenient way to achieve my goal? Do I have to use conditional variables or can I do this using sleep() variants?</p>