title: POSIX threads: the best interruption method
body: <p>The first thing, which I was told when had started working with pthreads, was - you should avoid force thread cancelation, like pthread_cancel. Instead we should use thread cancel notification via threads communication channel. </p>
  
  <p>If we have a really long task to run in the thread, we split this task into small chunks and check the cancelation flag after each chunk processing. Like this:</p>
  
  <pre><code>loop {
      process_chunk();
      if (check_cancel_flag())
          break;
  }
  </code></pre>
  
  <p>But what is the best approach for implementation of this check_cancel_flag() function?</p>
  
  <p>With all my experience in c and linux, I can remember only those methods:</p>
  
  <ol>
  <li><p>(If you have only one working thread) You can use sig_atomic_t as a type for the cancelation flag. Check it in check_cancel_flag() function and mark it as true in the thread` signal handler. Then just call pthread_kill from the main thread.</p></li>
  <li><p>Use any POD type for cancelation flag and protect it with a mutex. In this case you will get overhead with calling lock too often.</p></li>
  <li><p>Use mutex as cancelation flag. Check it with pthread_mutex_trylock call. If the main thread releases this mutex, it is time to shutdown for the worker thread.</p></li>
  <li><p>(For C11) Use gcc _atomic built-in functions (or another asm atomic library) to set and check cancelation flag.</p></li>
  </ol>
  
  <p>I could not remember nothing else.</p>
  
  <p>The question: How to choose correct approach?
  Do you know any bench mark about this problem?</p>