Alex Rivera | Logout

make main program wait for threads to finish

Asked 2011-06-24T12:40:09.330
12

In the following code I create some number of threads, and each threads sleeps for some seconds.

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.

Is there someway of making threads continue to run even though the calling thread finishes.

#include <pthread.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>


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<nThreads;i++){
    fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
    int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
    pthread_detach(thread1);
  }
  //  sleep(10);//work if this is not commented out.
  return 0;
}

Thanks

Edit:

Sorry for not clarifying, is it possible without explicitly keeping track of my current running threads and by using join.

Edit
Report

1 Answer

3

You need to join each thread you create:

int main()
{
    int                    nThreads = sample(1,10);
    std::vector<pthread_t> threads(nThreads);

    for(i=0; i<nThreads; i++)
    {
            pthread_create( &threads[i], NULL, worker, (void*) i)
    }

    /* Wait on the other threads */
    for(i=0; i<nThreads; i++)
    {
            status*   status;
            pthread_join(threads[i], &status);
    }
}
answered 2011-06-24T14:08:36.003

Your Answer