title: Cancelling thread that is stuck on epoll_wait
body: <p>I'm doing some event handling with C++ and pthreads. I have a main thread that reads from event queue I defined, and a worker thread that fills the event queue. The queue is of course thread safe.</p>
  
  <p>The worker thread have a list of file descriptors and create an epoll system call to get events on those file descriptors. It uses epoll_wait to wait for events on the fd's.</p>
  
  <p>Now the problem. Assuming I want to terminate my application cleanly, how can I cancel the worker thread properly? <code>epoll_wait</code> is not one of the cancellation points of <a href="http://man7.org/linux/man-pages/man7/pthreads.7.html" rel="noreferrer">pthread(7)</a> so it cannot react properly on <code>pthread_cancel</code>.</p>
  
  <p>The worker thread main() looks like this</p>
  
  <pre><code>while(m_WorkerRunning) {
      epoll_wait(m_EpollDescriptor, events, MAXEVENTS, -1);
      //handle events and insert to queue
  }
  </code></pre>
  
  <p>The <code>m_WorkerRunning</code> is set to <code>true</code> when the thread starts and it looks like I <strong>can</strong> interrupt the thread by settings <code>m_WorkerRunning</code> to false from the main thread. The problem is that <code>epoll_wait</code> theoretically can wait forever.</p>
  
  <p>Other solution I though about is: instead of waiting forever (-1) I can wait for example X time slots, then handle properly no-events case and if <code>m_WorkerRunning == false</code> then exit the loop and terminate the worker thread cleanly. The main thread then sets <code>m_WorkerRunning</code> to false, and sleeps X. However I'm not sure about the performance of such epoll_wait and also not sure what would be the correct X? 500ms? 1s? 10s?</p>
  
  <p>I'd like to hear some experienced advises!</p>
  
  <p>More relevant information: the fd's I'm waiting events on, are devices in <code>/dev/input</code> so technically I'm doing some sort of input subsystem. The targeted OS is Linux (latest kernel) on ARM architecture.</p>
  
  <p>Thanks!</p>