14.3 POSIX:SEM Unnamed Semaphores
A POSIX:SEM semaphore is a variable of type
with associated atomic operations for initializing, incrementing and
The following code segment declares a semaphore variable called sem .
#include <semaphore.h> sem_t sem;
The POSIX:SEM Extension does not specify the underlying type of sem_t . One possibility is that sem_t acts like a file descriptor and is an offset into a local table. The table values point to entries in a system table. A particular implementation may not use the file descriptor table model but instead may store information about the semaphore with the sem_t variable. The semaphore functions take a pointer to the semaphore variable as a parameter, so system implementers are free to use either model. You may not make a copy of a sem_t variable and use it in semaphore operations.
POSIX:SEM semaphores must be
SYNOPSIS #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned value); POSIX:SEM
. Interestingly, POSIX does not specify the return value on success, but the rationale mentions that
may be required to return 0 in a future specification. If
The following code segment initializes an unnamed semaphore to be used by threads of the process.
sem_t semA; if (sem_init(&semA, 0, 1) == -1) perror("Failed to initialize semaphore semA");
The sem_destroy function destroys a previously initialized unnamed semaphore referenced by the sem parameter.
SYNOPSIS #include <semaphore.h> int sem_destroy(sem_t *sem); POSIX:SEM
If successful, sem_destroy returns 0. If unsuccessful, sem_destroy returns “1 and sets errno . The sem_destroy function sets errno to EINVAL if *sem is not a valid semaphore.
The following code destroys semA .
sem_t semA; if (sem_destroy(&semA) == -1) perror("Failed to destroy semA");
What happens if Example 14.13; executes after
has already been
The POSIX standard states that the result of destroying a semaphore that has already been destroyed is undefined. The result of destroying a semaphore on which other threads are blocked is also undefined.