When is it safe to destroy a pthread barrier?

After pthread_barrier_wait() returns, all threads will have hit the barrier and are proceeding. Since only one thread is given the PTHREAD_BARRIER_SERIAL_THREAD return value, it's safe to use that to conditionally wrap the destruction code like so:

int rc = pthread_barrier_wait(&b)
if ( rc == PTHREAD_BARRIER_SERIAL_THREAD )
{
    pthread_barrier_destroy(&b);
}

Also, be aware that pthread_barrier_destroy() will return a result of EBUSY if the barrier was in use (i.e. another thread had called pthread_barrier_wait()).


The accepted answer is incorrect. A return value of PTHREAD_BARRIER_SERIAL_THREAD does not mean it is safe to destroy the barrier.

You need additional synchronization before destroying the barrier.

The problem is that a destroy call can occur whilst other threads are in the process of leaving the barrier. These threads need to check the state of the barrier due to the fact that the futex system call can have "false wakeups". If the memory used by the barrier is freed out from underneath them, then undefined behaviour will occur.

Thus the destroying thread needs to wait until all other threads have finished exiting the barrier. In order for that to happen, extra synchronization is required. Source with alternative implementation using pthread_cond

In this issue, the user is doing the same logic as you have in your example code. https://groups.google.com/forum/#!topic/thread-sanitizer/81idLTirikQ