Multithreaded Programming Guide

Counting Semaphores

Conceptually, a semaphore is a nonnegative integer count. Semaphores are typically used to coordinate access to resources, with the semaphore count initialized to the number of free resources. Threads then atomically increment the count when resources are added and atomically decrement the count when resources are removed.

When the semaphore count becomes zero, indicating that no more resources are present, threads trying to decrement the semaphore block wait until the count becomes greater than zero.

Table 4-7 Routines for Semaphores

"Initialize a Semaphore"

"sem_init(3R)"

"Increment a Semaphore"

"sem_post(3R)"

"Block on a Semaphore Count"

"sem_wait(3R)"

"Decrement a Semaphore Count"

"sem_trywait(3R)"

"Destroy the Semaphore State"

"sem_destroy(3R)"

Because semaphores need not be acquired and released by the same thread, they can be used for asynchronous event notification (such as in signal handlers). And, because semaphores contain state, they can be used asynchronously without acquiring a mutex lock as is required by condition variables. However, semaphores are not as efficient as mutex locks.

By default, there is no defined order of unblocking if multiple threads are waiting for a semaphore.

Semaphores must be initialized before use, but they do not have attributes.