Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Pthread Barriers in C Reusable?

So I know that you can create barriers in C to control the flow of a threaded program. You can initialize the barrier, have your threads use it, and then destroy it. However, I am unsure whether or not the same barrier can be reused (say if it were in a loop). Or must you use a new barrier for a second wait point? As an example, is the below code correct (reusing the same barrier)?

#include <pthread.h>
pthread_barrier_t barrier;

void* thread_func (void *not_used) {
     //some code
     pthread_barrier_wait(&barrier);
     //some more code
     pthread_barrier_wait(&barrier);
     //even more code
}

int main() {
    pthread_barrier_init (&barrier, NULL, 2);
    pthread_t tid[2];
    pthread_create (&tid[0], NULL, thread_func, NULL);
    pthread_create (&tid[1], NULL, thread_func, NULL);
    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    pthread_barrier_destroy(&barrier);
}
like image 809
Callahan Johnson Avatar asked Mar 30 '16 19:03

Callahan Johnson


1 Answers

Yes, they are reusable. The man page says:

When the required number of threads have called pthread_barrier_wait()...the barrier shall be reset to the state it had as a result of the most recent pthread_barrier_init() function that referenced it.

like image 187
kaylum Avatar answered Sep 20 '22 17:09

kaylum