man page(1)
Table of Contents

NAME

Sem_init, Sem_wait, Sem_signal - general semaphore primitives

SYNOPSIS

#include "sem.h"

typedef struct Sem_T { /* opaque! */
int count;
...
} Sem_T;

void Sem_init(Sem_T *s, long count);
void Sem_wait(Sem_T *s);
void Sem_signal(Sem_T *s);

DESCRIPTION

These functions implement general, distributed semaphores. A semaphore is a pointer to an instance of a Sem_T structure. This interface reveals the innards of Sem_Ts, but only so that they can be allocated statically or embedded in other structures. Clients must treat Sem_Ts as opaque and access their fields only via the functions in this interface. It is a checked runtime error to pass a NULL Sem_T* to any function in this interface.

Abstractly, a semaphore is a integer counter that can be incremented by 1, or decremented by 1 if it's positive. These operations are atomic.

Sem_init
accepts a pointer to a Sem_T and an initial value for its counter, initializes the semaphore's data structures and sets its counter to the specified initial value. Once initialized, a pointer to the Sem_T can be passed to the two functions described below.

Sem_wait
accepts a pointer to a Sem_T, waits for its counter to become positive, decrements the counter by 1, and returns. The caller waits for the counter to become positive; this operation is atomic.

Sem_signal
accepts a pointer to a Sem_T and increments its counter atomically. If other threads are waiting for the counter to become positive and the Sem_signal operation causes it to become positive, one of those threads will complete their call to Sem_wait. The queuing implicit in these operations is FIFO.

Semaphores can be used for mutual exclusion. For example,

Sem_T mutex;
Sem_new(&mutex, 1);
...
Sem_wait(&mutex);
...statements...
Sem_signal(&mutex);

creates and initializes a Sem_T*, and uses that pointer to insure that only one thread at a time executes statements. libthread.a library

SEE ALSO

chan(3), thread(3)

DIAGNOSTICS

Checked runtime errors are implemented with assertions; see assert(3).

BUGS

It is an unchecked runtime error to call Sem_init on the same Sem_T* more than once, to pass an uninitialized Sem_T* to Sem_wait or Sem_signal, or to access the fields of a Sem_T directly.


Table of Contents