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 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.
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.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With