pthread_cond_wait.3t (2010 09)
p
pthread_cond_wait(3T) pthread_cond_wait(3T)
(Pthread Library)
If a signal is delivered to a thread waiting for a condition variable, upon return from the signal handler,
the thread may return zero due to a spurious wakeup or continue waiting for the condition.
RETURN VALUE
pthread_cond_wait()
and pthread_cond_timedwait()
return the following values:
0 Successful completion.
<>0 Failure. An error number is returned to indicate the error. (The
errno variable is not set.)
ERRORS
The following error value is returned by
pthread_cond_timedwait()
if the corresponding condition
is detected.
[ETIMEDOUT] abstime has passed and a condition signal has not been received.
One of the following error values is returned by
pthread_cond_wait()
and
pthread_cond_timedwait()
if the corresponding condition is detected.
[EFAULT] A cond , mutex ,orabstime parameter points to an illegal address.
[EINVAL] The value specified by cond , mutex ,orabstime is invalid.
mutex is not owned by the calling thread. This error is not returned for a
PTHREAD_MUTEX_NO_OWNER_NP
, PTHREAD_MUTEX_NORMAL,or
PTHREAD_MUTEX_DEFAULT
mutex on HP-UX.
[EINVAL] Different mutexes are being used for cond . This error is not detected on HP-UX.
WARNINGS
It is important to note that when
pthread_cond_wait()
or pthread_cond_timedwait()
return
without error, the associated predicate may still be false. When
pthread_cond_timedwait()
returns with the timeout error, the associated predicate may be true. It is recommended that a condition
wait be enclosed in the equivalent of a "while loop," which checks the predicate.
Undefined behavior results if these functions are called with a
PTHREAD_MUTEX_RECURSIVE
mutex.
EXAMPLES
pthread_cond_wait()
is recommended to be used in a loop testing the predicate associated with it.
This will take care of any spurious wakeups that may occur.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
(void)pthread_mutex_lock(&mutex);
while (predicate == FALSE) {
(void)pthread_cond_wait(&cond, &mutex);
}
(void)pthread_mutex_unlock(&mutex);
pthread_cond_timedwait() is also recommended to be used in a loop. This function can return
success even if the predicate is not true. It should be called in a loop while checking the predicate. If the
function times out, the predicate may still have become true. The predicate should be checked before pro-
cessing the timeout case. The example given below does not do any other error checking.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct timespec abstime;
(void)pthread_mutex_lock(&mutex);
abstime = absolute time to timeout.
while (predicate == FALSE) {
ret = pthread_cond_timedwait(&cond, &mutex, &abstime);
if (ret == ETIMEDOUT) {
if (predicate == FALSE) {
/* Code for time-out condition */
} else {
2 Hewlett-Packard Company − 2 − HP-UX 11i Version 3: September 2010