I have a group of pthreads which all need to complete a task, then block until the last of them completes the task, then have all of them move onto the next task. This happens for many tasks.
I was thinking of having a counter, which starts equal to the number of threads at the beginning of each task and, as each thread finishes a task, it decrements it safely with a mutex until the last thread makes it zero. At the end of the task, all threads except the last one to complete would call pthread_cond_wait, and the last thread would call pthread_cond_broadcast to tell the other threads to move onto the next task. Then the last thread would not wait, and would instead continue onto this task too.
However, I am left with one problem. There is no guarantee that the second to last thread to decrement the counter will call pthread_cond_wait before the last thread calls pthread_cond_broadcast.
Is there any way in C and POSIX to handle this safely?
The tool you’re looking for is barriers.
Initialize the barrier with the number of threads that will be waiting to reach it:
Then, each thread calls:
The wait blocks until N threads are waiting on it, then all N wake up (conceptually) before any of them return from the wait call.