Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it safe to destroy a pthread barrier?

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);
  }
}
like image 1000
fmark Avatar asked May 17 '09 11:05

fmark


People also ask

What is Pthread barrier?

A Barrier in computing is a synchronization method where a group of threads cannot proceed until a condition allows the blocked threads to proceed. In this post we will construct an example of a Barrier that relates to men and women at the dinner table using pthreads.

How does Pthread barrier Wait work?

The functions create the barrier, specifying the number of threads that are synchronizing on the barrier, and set up threads to perform tasks and wait at the barrier until all the threads reach the barrier. When the last thread arrives at the barrier, all the threads resume execution.


1 Answers

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()).

like image 85
Jim Dovey Avatar answered Oct 13 '22 19:10

Jim Dovey