Semaphore

by Till Kaiser

Semaphore

by Till Kaiser

Object-oriented semaphores are not part of the C++ standard at this point. However, it is possible to implement a semaphore class using a mutex and a condition variable both of which where added to the standard in C++11.

For the implementation shown on this website the function names where derived from the POSIX semaphores. The post function increases the count of the semaphore and notifies a thread that might be waiting on the semaphore if its count is at zero. The wait function decreases the semaphore count and blocks if the count reaches zero. Any thread calling wait when the count is at zero waits on the condition variable until notified that the count has increased.

A variation on this function is the try_wait function which does not block but simply return its success in acquiring the semaphore in the form of a bool.

Related