sem_timedwait(), sem_timedwait_monotonic()

Ожидать на именованном или безымянном семафоре с заданным тайм-аутом

Прототип:

#include <semaphore.h>
#include <time.h>
int sem_timedwait( sem_t *sem,
const struct timespec *abs_timeout );
int sem_timedwait_monotonic( sem_t *sem,
const struct timespec *abs_timeout );

Аргументы:

sem
The semaphore that you want to wait on.
abs_timeout
A pointer to a struct timespec that specifies the maximum time to wait to lock the semaphore, expressed as an absolute time.

Библиотека:

libc

Описание:

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 is based on the CLOCK_REALTIME clock.

The sem_timedwait_monotonic() function is a ЗОСРВ «Нейтрино» extension; it's similar to sem_timedwait(), but it uses CLOCK_MONOTONIC, so the timeout isn't affected by changes to the system time.

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.

Возвращаемое значение:

0
The calling process successfully performed the semaphore lock operation on the semaphore designated by sem.
-1
Возникла ошибка. Состояние семафора не изменено. Код ошибки записан в errno.

Коды ошибок:

EDEADLK
A deadlock condition was detected.
EINTR
A signal interrupted this function.
EINVAL
Invalid semaphore sem, or the thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than zero or greater than or equal to 1000 million.
ETIMEDOUT
The semaphore couldn't be locked before the specified timeout expired.

Примеры:

#include <stdio.h>
#include <semaphore.h>
#include <time.h>
void 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;
}

Классификация:

sem_timedwait() — POSIX 1003.1 SEM TMO; sem_timedwait_monotonic() — ЗОСРВ «Нейтрино»

Точка остановки потока
Да
Обработчик прерываний
Нет
Обработчик сигналов
Да
В потоке
Да

Тематические ссылки:

sem_post(), sem_trywait(), sem_wait(), time(), struct timespec




Предыдущий раздел: Описание API системной библиотеки