Multithreaded Programming Guide

Blocking Until a Specified Time

Use pthread_cond_timedwait(3C) 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 Syntax

int pthread_cond_timedwait(pthread_cond_t *restrict cv,
          pthread_mutex_t *restrict mp, 
          const struct timespec *restrict 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); 

pthread_cond_timedwait() always returns with the mutex locked and owned by the calling thread, even when pthread_cond_timedwait() is returning an error.

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.



Example 4–9 Timed Condition Wait

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

pthread_cond_timedwait Return Values

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


EINVAL

Description:

cv, mp, or abstime points to an illegal address.


EINVAL

Description:

Different mutexes were supplied for concurrent pthread_cond_timedwait() operations on the same condition variable.


ETIMEDOUT

Description:

The time specified by abstime has passed.


EPERM

Description:

The mutex was not owned by the current thread at the time of the call.

The timeout 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.