title: How can I kill a pthread that is in an infinite loop, from outside that loop?
body: <p>I create a thread and I put it into an infinite loop. I get memory leaks when checking the code with <em>valgrind</em>. Here is my code:</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;time.h&gt;
  
  void thread_do(void){
      while(1){}
  }
  
  int main(){
      pthread_t th;   
      pthread_create(&amp;th, NULL, (void *)thread_do, NULL);
  
      sleep(2);
      /* I want to kill thread here */
      sleep(2);
      return 0;
  }
  </code></pre>
  
  <p>So a thread is created in main and just runs thread_do() all the time. Is there a way to kill it from inside <em>main</em> after 2 seconds? I have tried both <code>pthread_detach(th)</code> and <code>pthread_cancel(th)</code> but I still get leaks.</p>