views:

45

answers:

1

I have multiple threads, and I want each thread to wait for every others to complete at certain point in the code before proceeding as following:

void *run() { 
  for (i=0;i<1000;i++){
    do_1st();
    // sync() all stop here wait for all then resume
    do_2nd();
  }
}

I tried to use pthread_cond_wait.. but It seems very complicated.

Is there any easy wait to do this ?

Thank you

+5  A: 

You can use a pthread_barrier, initialize it before you start your threads, and set the count to the no. of threads that's running your loop. e.g. if you have 8 threads:

pthread_barrier_init(&my_barrier,NULL,8);

The thread loop now becomes

void *run() { 
  for (i=0;i<1000;i++){
    do_1st();
    pthread_barrier_wait(&my_barrier);
    do_2nd();
  }
}
nos
this is exactly what I need ! thx nos. btw do i need to destroy the barrier after used ?
iKid
You should, yes - though if you're running your threads in several batches, you can reuse it. If your application exits when you're done with those calculations, it'll be cleaned up on process exit.
nos