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);
}
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.
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