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?
The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition variable. They are called with mutex locked by the calling thread or undefined behaviour will result.
The pthread_cond_wait() routine always returns with the mutex locked and owned by the calling thread, even when returning an error. This function blocks until the condition is signaled. The function atomically releases the associated mutex lock before blocking, and atomically acquires the mutex again before returning.
You still need to check your predicate regardless to account for potential spurious wakeups. The purpose of the mutex is not to protect the condition variable; it is to protect the predicate on which the condition variable is being used as a signaling mechanism.
It is unspecified as exaclty what constitutes as invalid, but here are a few reasons that I have observed pthread_cond_timedwait
returning EINVAL
:
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
.
I'd like to share my experience on this issue, the time value is 'timespec', and its 'tv_nsec' range should be kept inside [0, 999999999], thus if you set the nano value more than 1 second, some linux may return EINVAL!
struct timespec {
time_t tv_sec; /* Seconds */
long tv_nsec; /* Nanoseconds [0 .. 999999999] */
};
Hope this help you out of trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With