Barrier is a mechanism in Pthread to queue up a definite number of threads before the execution of sequences of codes. It comes in handy when the order of memory access is critical for the program especially if the main function is depends on #routines execution or routines are dependent of each other.
To use a barrier, declare a pthread_barrier_t
object and initialise it by calling the function pthread_barrier_init
and specify how many threads that this barrier should wait for. After that, call pthread_barrier_wait
to activate the queue. At last, do not forget to clean up the barrier by calling pthread_barrier_destroy
.
pthread_barrier_t barrier;
// in the program
pthread_barrier_init(&barrier, NULL, 5); // specify the number of threads that this barrier should wait
// at somewhere
pthread_barrier_wait(&barrier);
// at the end of the program
pthread_barrier_destroy(&barrier);
Note: This is much different to 202112061117 since it does not actually lock down a certain portion of codes.