title: Rerunning cancelled pthread
body: <p>My problem is that I cannot reuse cancelled pthread. Sample code:</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  
  pthread_t alg;
  pthread_t stop_alg;
  int thread_available;
  
  void *stopAlgorithm() {
      while (1) {
          sleep(6);
          if (thread_available == 1) {
              pthread_cancel(alg);
              printf("Now it's dead!\n");
              thread_available = 0;
          }
      }
  }
  void *algorithm() {
      while (1) {
          printf("I'm here\n");
      }
  }
  
  int main() {
      thread_available = 0;
      pthread_create(&amp;stop_alg, NULL, stopAlgorithm, 0);
      while (1) {
          sleep(1);
          if (thread_available == 0) {
              sleep(2);
              printf("Starting algorithm\n");
              pthread_create(&amp;alg, NULL, algorithm, 0);
              thread_available = 1;
          }
      }
  }
  </code></pre>
  
  <p>This sample should create two threads - one will be created at the program beginning and will try to cancel second as soon it starts, second should be rerunned as soon at it was cancelled and say "I'm here". But when algorithm thread cancelled once it doesn't start once again, it says "Starting algorithm" and does nothing, no "I'm here" messages any more. Could you please tell me the way to start cancelled(immediately stopped) thread once again?</p>
  
  <p>UPD: So, thanks to your help I understood what is the problem. When I rerun algorithm thread it throws error 11:"The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process <code>PTHREAD_THREADS_MAX</code> would be exceeded.". Actually I have 5 threads, but only one is cancelled, others stop by pthread_exit. So after algorithm stopped and program went to standby mode I checked status of all threads with <code>pthread_join</code> - all thread show 0(cancelled shows <code>PTHREAD_CANCELED</code>), as far as I can understand this means, that all threads stopped successfully. But one more try to run algorithm throws error 11 again. So I've checked memory usage. In standby mode before algorithm - 10428, during the algorithm, when all threads used - 2026m, in standby mode after algorithm stopped - 2019m. So even if threads stopped they still use memory, <code>pthread_detach</code> didn't help with this. Are there any other ways to clean-up after threads?</p>
  
  <p>Also, sometimes on pthread_cancel my program crashes with "libgcc_s.so.1 must be installed for pthread_cancel to work"</p>