Search code examples
cmultithreadingposixc11

What is the return value of spurious wake-ups?


In C11, the cnd_timedwait function is defined as followed:

int cnd_timedwait( cnd_t* restrict cond, mtx_t* restrict mutex,
                   const struct timespec* restrict time_point );

Atomically unlocks the mutex pointed to by mutex and blocks on the condition variable pointed to by cond until the thread is signalled by cnd_signal or cnd_broadcast, or until the TIME_UTC based time point pointed to by time_point has been reached, or until a spurious wake-up occurs. The mutex is locked again before the function returns.

Return value

thrd_success if successful, thrd_timedout if the timeout time has been reached before the mutex is locked, or thrd_error if an error occurred.

When spurious wake-ups occur, would the function return thrd_success or thrd_error?

Although as far as I know, a spurious wake-up is not technically seen as an error.


Solution

  • If cnd_timedwait could tell that the wake-up was spurious, it wouldn't do it. It doesn't do spurious wake-ups just to troll you. They happen because the value of the condition can change after the wake-up is scheduled but before the woken-up thread manages to do anything.

    Since cnd_timedwait cannot tell whether a return is spurious or not, it's return value can't reflect that fact. It's a normal successful return. Your first task is to verify the condition.