next up previous contents
Next: Sync Objects: Condition Variable Up: The Fully Portable Subsystems Previous: Thread System   Contents

Subsections

Sync Objects: Semaphore

Semaphores should be familiar to most computer science people and programmers. A semaphore is a counted sync primitive. The best analogy for this is a bank. In a bank, you have N tellers and M customers. Each customer can either go directly to an open window, or must take a ticket and wait until a teller is available.

In concise terms, each semaphore contains a count value. When a thread wants to use the limited resource represented by the semaphore, it must call sem_wait or sem_wait_timed. If the count is greater than zero, then the count is decreased and the thread is allowed to continue, all in an atomic and thread-safe manner. If the count is already zero, then the thread is placed on a queue and must sleep until another thread performs a sem_signal. That function checks to see if anyone is waiting and wakes them. In this way, control is very efficiently passed between waiting threads.

A very simple condition variable can be created by using a semaphore with an initial count of zero. A mutex can be created by using an initial count of one. For this reason, semaphores are mostly considered to be the fundamental thread sync primitive.

semaphore_t * sem_create(int value)

Create and return a new semaphore with an initial value of value.

void sem_destroy(semaphore_t * sem)

Destroy a previously created semaphore.

void sem_wait(semaphore_t * sem)

``Wait'' on the given semaphore. The operation is described above.

int sem_wait_timed(semaphore_t * sem, int timeout)

``Wait'' on the given semaphore for a maximum of timeout milliseconds. If the semaphore has not been signaled in that time, then return with an error code (negative value).

void sem_signal(semaphore_t * sem)

``Signal'' on the given semaphore. Any waiting thread will be placed back on the scheduler's ready queue.

int sem_count(semaphore_t * sem)

Return the current count of the semaphore. Note that although this may be used to check if it's likely that the thread will be put to sleep, this is not an entirely reliable way to check this because of race condition issues.


next up previous contents
Next: Sync Objects: Condition Variable Up: The Fully Portable Subsystems Previous: Thread System   Contents
Dan Potter 2002-07-29