macOS: pthread_barrier_wait impropper wait condition
Youw opened this issue · 0 comments
Youw commented
Found by Coverity:
static int pthread_barrier_wait(pthread_barrier_t *barrier)
{
// lock_acquire: Calling pthread_mutex_lock acquires lock pthread_barrier.mutex.
pthread_mutex_lock(&barrier->mutex);
++(barrier->count);
// if_insufficient: This if cannot adequately check the wait condition, as it does not cause the thread to wait again if the wait ends due to a spurious wakeup.
if(barrier->count >= barrier->trip_count)
{
barrier->count = 0;
pthread_cond_broadcast(&barrier->cond);
pthread_mutex_unlock(&barrier->mutex);
return 1;
}
else
{
// CID undefined (#1 of 1): Data race condition (BAD_CHECK_OF_WAIT_COND)
// wait_cond_improperly_checked: The wait condition prompting the wait upon pthread_barrier.mutex is not checked correctly. If a spurious wakeup occurs, the thread could continue its task before the wait condition is satisfied.
Refactor the code to protect the call to wait with a loop that rechecks the wait condition inside the locked region.
pthread_cond_wait(&barrier->cond, &(barrier->mutex));
pthread_mutex_unlock(&barrier->mutex);
return 0;
}
}