Wait on a condition variable, with a time limit
#include <pthread.h> #include <time.h> int pthread_cond_timedwait( pthread_cond_t* cond, pthread_mutex_t* mutex, const struct timespec* abstime );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The pthread_cond_timedwait() function blocks the calling thread on the condition variable cond, and unlocks the associated mutex mutex. The calling thread must have locked mutex before waiting on the condition variable. Upon return from the function, the mutex is again locked and owned by the calling thread.
The calling thread is blocked until either another thread performs a signal or broadcast on the condition variable, the absolute time specified by abstime has passed, a signal is delivered to the thread, or the thread is canceled (waiting on a condition variable is a cancellation point). In all cases, the thread reacquires the mutex before being unblocked.
To specify the clock source for the condvar, call pthread_condattr_setclock(). As discussed in "Advanced topics" in the Clocks, Timers, and Getting a Kick Every So Often chapter of Getting Started with QNX Neutrino, CLOCK_MONOTONIC isn't affected by changes to the system time; the default, CLOCK_REALTIME, is.
If a thread that's blocked on a condition variable is canceled, the thread reacquires the mutex that's guarding the condition variable, so that the thread's cleanup handlers run in the same state as the critical code before and after the call to this function. If some other thread owns the lock, the canceled thread blocks until the mutex is available.
Wait five seconds while trying to acquire control over a condition variable:
#include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c; int main(int argc, char* argv[]) { struct timespec to; int retval; pthread_condattr_t attr; fprintf(stderr, "starting...\n"); /* Set up the condvar attributes to use CLOCK_MONOTONIC. */ pthread_condattr_init( &attr); pthread_condattr_setclock( &attr, CLOCK_MONOTONIC); pthread_cond_init( &c, &attr); /* Here's the interesting bit; we'll wait for five seconds FROM NOW when we call pthread_cond_timedwait(). */ clock_gettime(CLOCK_MONOTONIC, &to); to.tv_sec += 5; if ((retval = pthread_mutex_lock(&m))) { fprintf(stderr, "pthread_mutex_lock %s\n", strerror(retval)); exit(EXIT_FAILURE); } if ((retval = pthread_cond_timedwait(&c, &m, &to))) { fprintf(stderr, "pthread_cond_timedwait %s\n", strerror(retval)); exit(EXIT_FAILURE); } if ((retval = pthread_mutex_unlock(&m))) { fprintf(stderr, "pthread_mutex_unlock %s\n", strerror(retval)); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |