pthread_cond_timedwait() root causes of EINVAL

pthreads

Solution

It is unspecified as exaclty what constitutes as invalid, but here are a few reasons that I have observed `pthread_cond_timedwait` returning `EINVAL`:

- The condition and/or mutex was not initialized properly. Check the initialization return results, and verify that the correct pthread library is explicitly being linked. Sporadic issues may occur when various versions of glibc are linked, resulting in difficult to debug cases where the init call returns success, but the object is not correctly initialized.

- Any undefined behavior may result in an invalid internal state, which may or may not be detected by the pthread calls. Undefined behavior can result from:

- Initializing the mutex or condition variable more than once without it being destroyed.

- Using the mutex or condition variable after it has been destroyed, but before it has been re-initialized.

- The condition and/or mutex was manually written over by application code.

- The mutex or condition variable was destroyed while a thread was waiting on the object.

- Different mutexes are used with the same condition variable.

- The abstime argument had a tv_nsec value of less than 0 or greater than 1,000,000,000.

Without manually mimicking the validation calls that pthread is doing, then I do not know of a way to check the arguments before calling `pthread_cond_timewait()`. However, `pthread_cond_timewait()` returning `EINVAL` should not cause a fatal crash, as it is a specified case. Consider examining other areas of application code that may not handle the return results appropriately. For example, code that assumes success as long as the return was not `ETIMEDOUT`.

Problem

I am seeing in very rare cases `pthread_cond_timedwait()` return `EINVAL` and cause a fatal crash on our system. I understand that this means one of the parameters passed in has to be invalid, but how does the mutex or cond variable become invalid? Is there any way to check these arguments before calling `pthread_cond_timedwait()` to prevent a crash?

Original source