Multithreaded Programming Guide

Block Until a Specified Event

pthread_cond_timedwait(3T)

Prototype:
int	pthread_cond_timedwait(pthread_cond_t *cv,
    pthread_mutex_t *mp, const struct timespec *abstime);
#include <pthread.h>
#include <time.h>

pthread_cond_t cv;
pthread_mutex_t mp;
timestruct_t abstime;
int ret;

/* wait on condition variable */
ret = pthread_cond_timedwait(&cv, &mp, &abstime); 

Use pthread_cond_timedwait(3T) as you would use pthread_cond_wait(), except that pthread_cond_timedwait() does not block past the time of day specified by abstime. pthread_cond_timedwait() always returns with the mutex locked and owned by the calling thread, even when it is returning an error. (For Solaris threads, see "cond_timedwait(3T)".)

The pthread_cond_timedwait() function blocks until the condition is signaled or until the time of day, specified by the last argument, has passed.


Note -

pthread_cond_timedwait() is also a cancellation point.


Return Values

pthread_cond_timedwait() returns zero after completing successfully. Any other returned value indicates that an error occurred. When either of the following conditions occurs, the function fails and returns the corresponding value.


EINVAL

cv or abstime points to an illegal address.


ETIMEDOUT

The time specified by abstime has passed.

The time-out is specified as a time of day so that the condition can be retested efficiently without recomputing the value, as shown in Example 4-9.


Example 4-9 Timed Condition Wait

pthread_timestruc_t to;
pthread_mutex_t m;
pthread_cond_t c;
...
pthread_mutex_lock(&m);
to.tv_sec = time(NULL) + TIMEOUT;
to.tv_nsec = 0;
while (cond == FALSE) {
    err = pthread_cond_timedwait(&c, &m, &to);
    if (err == ETIMEDOUT) {
        /* timeout, do something */
        break;
    }
}
pthread_mutex_unlock(&m);