Are Pthread Barriers in C Reusable?
Asked Answered
G

1

10

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);
}
Georgettegeorgi answered 30/3, 2016 at 19:57 Comment(2)
What was the function value returned by pthread_barrier_init? And the other functions?Fillagree
A barrier does not "control the flow", but is a synchronisation point. Program flow is controlled by conditional statements, etc.Calamite
B
16

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.

Brynnbrynna answered 30/3, 2016 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.