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

Operation 

Destination Discussion 

Initialize a semaphore 

sem_init(3RT)

Increment a semaphore 

sem_post(3RT)

Block on a semaphore count 

sem_wait(3RT)

Decrement a semaphore count 

sem_trywait(3RT)

Destroy the semaphore state 

sem_destroy(3RT)

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.