Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.10 POSIX Semaphores 581


Thesem_unlinkfunction removes the name of the semaphore. If thereare noopen
references to the semaphore, then it is destroyed. Otherwise, destruction is deferred
until the last open reference is closed.
Unlike with XSI semaphores, we can only adjust the value of a POSIX semaphoreby
one with a single function call. Decrementing the count is analogous to locking a binary
semaphore or acquiring a resource associated with a counting semaphore.

Note that there is no distinction of semaphoretype with POSIX semaphores. Whether we use
abinary semaphore or a counting semaphoredepends on how we initialize and use the
semaphore. Ifasemaphoreonly ever has a value of 0 or 1, then it is a binary semaphore.
When a binary semaphorehas a value of 1, we say that it is ‘‘unlocked;’’when it has a value of
0, we say that it is ‘‘locked.’’

To decrement the value of a semaphore, we can use either the sem_waitor
sem_trywaitfunction.

#include <semaphore.h>
int sem_trywait(sem_t *sem);
int sem_wait(sem_t *sem);
Both return: 0 if OK,−1 on error
With thesem_waitfunction, we will block if the semaphorecount is 0. We won’t
return until we have successfully decremented the semaphorecount or areinterrupted
by a signal.We can use thesem_trywaitfunction to avoid blocking. If the semaphore
count is zerowhen we callsem_trywait, it will return−1witherrnoset toEAGAIN
instead of blocking.
Athirdalternative is to block for a bounded amount of time. We can use the
sem_timedwaitfunction for this purpose.
#include <semaphore.h>
#include <time.h>
int sem_timedwait(sem_t *restrictsem,
const struct timespec *restrict tsptr);
Returns: 0 if OK,−1 on error
Thetsptrargument specifies the absolute time when we want to give up waiting for the
semaphore. The timeout is based on theCLOCK_REALTIMEclock (recall Figure6.8). If
the semaphorecan be decremented immediately,then the value of the timeout doesn’t
matter — even though it might specify some time in the past, the attempt to decrement
the semaphorewill still succeed. If the timeout expires without being able to decrement
the semaphorecount, then sem_timedwait will return −1with errno set to
ETIMEDOUT.
To increment the value of a semaphore, we call thesem_postfunction. This is
analogous to unlocking a binary semaphore or releasing a resource associated with a
counting semaphore.
Free download pdf