Simox  2.3.74.0
simox::threads::CountingSemaphore Class Reference

A counting semaphore. More...

Public Member Functions

 CountingSemaphore ()
 Construct an initially blocking semaphore (initial count 0) without max count. More...
 
 CountingSemaphore (unsigned int count)
 Construct a semaphore with the given initial count without max count. More...
 
 CountingSemaphore (unsigned int count, unsigned int maxCount)
 Construct a semaphore with the given initial count and max count. More...
 
void notify ()
 Signal that one waiting thread may continue. More...
 
void wait ()
 Wait until a thread may enter. More...
 
bool try_wait ()
 Try to enter. More...
 

Detailed Description

A counting semaphore.

Threads can enter when the internal count is > 0. Notifiying the semaphore increments the count and allows threads to enter. A thread can wait until it may enter. When it enters, it decrements the internal count. An optional max count can limit the value of count (useful e.g. when your buffer has a limited number of items).

A counting semaphore can be used e.g. in Producer-Consumer patterns. The producer signals new jobs/items via notify(), while the consumer waits for new jobs via wait().

Constructor & Destructor Documentation

◆ CountingSemaphore() [1/3]

simox::threads::CountingSemaphore::CountingSemaphore ( )

Construct an initially blocking semaphore (initial count 0) without max count.

◆ CountingSemaphore() [2/3]

simox::threads::CountingSemaphore::CountingSemaphore ( unsigned int  count)

Construct a semaphore with the given initial count without max count.

Parameters
countThe initial count (0 to block initially).

◆ CountingSemaphore() [3/3]

simox::threads::CountingSemaphore::CountingSemaphore ( unsigned int  count,
unsigned int  maxCount 
)

Construct a semaphore with the given initial count and max count.

Parameters
countThe initial count (0 to block initially).
maxCountAn optional count limit (1 for a binary semaphore).

Member Function Documentation

◆ notify()

void simox::threads::CountingSemaphore::notify ( )

Signal that one waiting thread may continue.

Also known as post() or signal(). Increments the count by 1, if it is below the optional max count.

◆ try_wait()

bool simox::threads::CountingSemaphore::try_wait ( )

Try to enter.

If the semaphore is currently blocking, return false. If the semaphore is free (count > 0), decrement the count and return true.

Returns
True if entering was successful, false if semaphore was blocking.

◆ wait()

void simox::threads::CountingSemaphore::wait ( )

Wait until a thread may enter.

Decrements the count when resuming.