![]() |
![]() |
![]() |
![]() |
![]() |
This version of this document is no longer maintained. For the latest documentation, see http://www.qnx.com/developers/docs. |
Wait on a semaphore, with a timeout
#include <semaphore.h>
#include <time.h>
int sem_timedwait(
sem_t * sem,
const struct timespec * abs_timeout );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The sem_timedwait() function locks the semaphore referenced by sem as in the sem_wait() function. However, if the semaphore can't be locked without waiting for another process or thread to unlock the semaphore by calling sem_post(), the wait is terminated when the specified timeout expires.
The timeout expires when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (i.e. when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call. The timeout is based on the CLOCK_REALTIME clock.
#include <stdio.h>
#include <semaphore.h>
#include <time.h>
main(){
struct timespec tm;
sem_t sem;
int i=0;
sem_init( &sem, 0, 0);
do {
clock_gettime(CLOCK_REALTIME, &tm);
tm.tv_sec += 1;
i++;
printf("i=%d\n",i);
if (i==10) {
sem_post(&sem);
}
} while ( sem_timedwait( &sem, &tm ) == -1 );
printf("Semaphore acquired after %d timeouts\n", i);
return;
}
| Safety: | |
|---|---|
| Cancellation point | Yes |
| Interrupt handler | No |
| Signal handler | Yes |
| Thread | Yes |
sem_post(), sem_trywait(), sem_wait(), time(), timespec
![]() |
![]() |
![]() |
![]() |