title: make main program wait for threads to finish
body: <p>In the following code I create some number of threads, and each threads sleeps for some seconds.</p>
  
  <p>However my main program doesn't wait for the threads to finish, I was under the assumption that threads would continue to run until they finished by themselves.</p>
  
  <p>Is there someway of making threads continue to run even though the calling thread finishes.</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;iostream&gt;
  #include &lt;cstdio&gt;
  #include &lt;cstdlib&gt;
  
  
  int sample(int min,int max){
    int r=rand();
    return (r %max+min );
  }
  
  
  
  void *worker(void *p){
    long i = (long) p;
    int s = sample(1,10);
    fprintf(stdout,"\tid:%ld  will sleep: %d \n",i,s);
    sleep(s);
    fprintf(stdout,"\tid:%ld  done sleeping \n",i,s);
  }
  
  pthread_t thread1;
  
  int main(){
    int nThreads = sample(1,10);
  
    for(int i=0;i&lt;nThreads;i++){
      fprintf(stderr,"\t-&gt; Creating: %d of %d\n",i,nThreads);
      int iret1 = pthread_create( &amp;thread1, NULL, worker, (void*) i);
      pthread_detach(thread1);
    }
    //  sleep(10);//work if this is not commented out.
    return 0;
  }
  </code></pre>
  
  <p>Thanks</p>
  
  <p>Edit:</p>
  
  <p>Sorry for not clarifying, is it possible without explicitly keeping track of my current running threads and by using join.</p>