views:

322

answers:

1

If I have an initialised pthread_barrier_t, when is it safe to destroy it? Is the following example safe?

pthread_barrier_t barrier;
...
int rc = pthread_barrier_wait(b);
if (rc != PTHREAD_BARRIER_SERIAL_THREAD && rc != 0){
  perror("pthread_barrier_wait");
  exit(1);
}

if (id == 0){
  if(pthread_barrier_destroy(&(threads[t_root].info.tmp_barrier))){
    perror("pthread_barrier_destroy");
    exit(1);
  }
}
A: 

After pthread_barrier_wait() returns, all threads will have hit the barrier and are proceeding. Since only one thread is given the PTHREAD_BARRIER_SERIAL_THREAD return value, it's safe to use that to conditionally wrap the destruction code like so:

int rc = pthread_barrier_wait(&b)
if ( rc == PTHREAD_BARRIER_SERIAL_THREAD )
{
    pthread_barrier_destroy(&b);
}

Also, be aware that pthread_barrier_destroy() will return a result of EBUSY if the barrier was in use (i.e. another thread had called pthread_barrier_wait()).

Jim Dovey