title: How do I wake up a sleeping pthread?
body: <p>I'm writing a program in C++.  I've noticed that it's gaining a number of threads whose purpose is to do something at intervals, there are 3 or 4 of them.  I decided to refactor by writing a scheduler service that the other places that use these threads could subscribe to, which should reduce the number of extra event threads I have running at any time to just one.</p>
  
  <p>I don't have any code that uses this yet; before I start writing it I'd like to know if it's possible, and get some feedback on my design.  A brief description of what I'd like to accomplish is this:</p>
  
  <p><strong>To add an event</strong></p>
  
  <ol>
  <li>Caller provides an event and a schedule</li>
  <li>Schedule provides the next occurrence of the event</li>
  <li>(event, schedule) pair is added to an event queue</li>
  <li><em>interrupt sleeping event thread (i.e. wake it up)</em></li>
  </ol>
  
  <p><strong>The event thread main loop</strong></p>
  
  <ol>
  <li>try to get the next event in the event queue</li>
  <li>If there is no pending event, go straight to 4</li>
  <li>Get the time that the next event is supposed to occur</li>
  <li>Sleep until next event (or forever if no waiting event)</li>
  <li>If sleeping was interrupted for any reason, loop back to 1</li>
  <li>If sleeping completed successfully, perform current event</li>
  <li>Update queue (remove event, re-insert if it's a repeating event)</li>
  <li>Jump back to 1</li>
  </ol>
  
  <p>I've done a bit of research and know that it's possible to interrupt a sleeping thread, and I believe that as long as simultaneous access to the event queue is prevented, there shouldn't be any dangerous behavior.  I'd imagine that waking a thread HAS to be possible, java's Thread's sleep() call throws an InterruptedException under some circumstances, and unless it doesn't rely on the operating system's underlying sleep call, it's got to be possible somehow.</p>
  
  <h1>Question</h1>
  
  <p>Can anyone comment on my approach?  Is this a wheel I'd be better off not reinventing?  How, specifically, can you interrupt a sleeping thread such that execution resumes at the next instruction, and is it possible to detect this from the interrupted thread?</p>
  
  <p><strong>A note about boost</strong></p>
  
  <p>I'd bet you can write a scheduler with boost, but this compiles and runs on a machine that's, for lack of a better phrase, a load of crap.  I've compiled boost programs before on it, and each file that pulls boost in usually takes upwards of 30 seconds to compile.  If I can avoid this irritating development obstacle, I'd very much like to.</p>
  
  <h1>Addendum - Working Code [Amended as per caf's suggestion]</h1>
  
  <p>This is the code I've produced that works.  It's been rudimentarily tested but has properly handled both single and repeated events with varying delays.</p>
  
  <p>Here's the event thread's body:</p>
  
  <pre><code>void Scheduler::RunEventLoop()
  {
      QueueLock();                   // lock around queue access
      while (threadrunning)
      {
          SleepUntilNextEvent();     // wait for something to happen
  
          while (!eventqueue.empty() &amp;&amp; e.Due())
          {                          // while pending due events exist
              Event e = eventqueue.top();
              eventqueue.pop();
  
              QueueUnlock();         // unlock
              e.DoEvent();           // perform the event
              QueueLock();           // lock around queue access
  
              e.Next();              // decrement repeat counter
                                     // reschedule event if necessary
              if (e.ShouldReschedule()) eventqueue.push(e);
          }
      }
      QueueUnlock();                 // unlock
      return;                        // if threadrunning is set to false, exit
  }
  </code></pre>
  
  <p>Here's the sleep function:</p>
  
  <pre><code>void Scheduler::SleepUntilNextEvent()
  {
      bool empty = eventqueue.empty();  // check if empty
  
      if (empty)
      {
          pthread_cond_wait(&amp;eventclock, &amp;queuelock); // wait forever if empty
      }
      else
      {
          timespec t =                  // get absolute time of wakeup
              Bottime::GetMillisAsTimespec(eventqueue.top().Countdown() + 
                                           Bottime::GetCurrentTimeMillis());
          pthread_cond_timedwait(&amp;eventclock, &amp;queuelock, &amp;t); // sleep until event
      }
  }
  </code></pre>
  
  <p>Finally, AddEvent:</p>
  
  <pre><code>void Scheduler::AddEvent(Event e)
  {
      QueueLock();
      eventqueue.push(e);
      QueueUnlock();
      NotifyEventThread();
  }
  </code></pre>
  
  <p>Relevant variable declarations:</p>
  
  <pre><code>bool threadrunning;
  priority_queue&lt;Event, vector&lt;Event&gt;, greater&lt;Event&gt; &gt; eventqueue;
  pthread_mutex_t queuelock; // QueueLock and QueueUnlock operate on this
  pthread_cond_t eventclock;
  </code></pre>
  
  <p>To deal with the issue of generic events, each <code>Event</code> contains a pointer to an object of abstract type <code>action</code>, whos subclasses override <code>action::DoEvent</code>.  this method is called from inside <code>Event::DoEvent</code>.  <code>actions</code> are 'owned' by their events, i.e. they are automatically deleted if the event no longer needs to be rescheduled.</p>