help icon indicating copy to clipboard operation
help copied to clipboard

"spurious wakeups" with uv_cond_wait?

Open bnoordhuis opened this issue 5 years ago • 2 comments

quick question; what exactly does the documentation mean by expecting "spurious wakeups" with uv_cond_wait? Am I to not rely on a conditional wait only proceeding on a condition signalling from another thread, or does this mean something else?

Originally posted by @brandonpoc in https://github.com/libuv/libuv/pull/1639#issuecomment-605776019

bnoordhuis avatar Mar 30 '20 10:03 bnoordhuis

@brandonpoc A spurious wakeup is where the "wait on condition variable" function returns without the condition variable having actually been signaled, e.g., because of the delivery of a (UNIX) signal.

That's why a condition variable is always coupled with some predicate to test for. Here's an example from libuv's semaphore emulation code:

static void uv__custom_sem_wait(uv_sem_t* sem_) {
  uv_semaphore_t* sem;

  sem = *(uv_semaphore_t**)sem_;
  uv_mutex_lock(&sem->mutex);
  while (sem->value == 0)
    uv_cond_wait(&sem->cond, &sem->mutex);
  sem->value--;
  uv_mutex_unlock(&sem->mutex);
}

The predicate here is the while (sem->value == 0) check.

bnoordhuis avatar Mar 30 '20 10:03 bnoordhuis

Thank you for clearing that up!

brandonpoc avatar Apr 01 '20 01:04 brandonpoc