counting_semaphore


A counting semaphore is a generalization of a mutex semaphore that allows multiple resources to be locked and unlocked. Threads can use the blocking method lock() to acquire a single resource, or they can use the method try_lock() to attempt acquisition of one or more resources without blocking.

Unlike the os_mutex_semaphore , an os_counting_semaphore is not owned by a particular thread; it is simply owned. One thread can wait() and a different thread can post() to increase the available resource count and unblock waiters. Contrast this with an os_mutex_semaphore , where the same thread that waits (and acquires the resource) must also post to release the resource.

Library

Thread<ToolKit>

Declaration

#include <ospace/thread/counting.h>

class os_counting_semaphore

Typedefs

typedef os_counting_semaphore os_semaphore

Interface

Constructor
os_counting_semaphore( unsigned int initial )
Constructs a counting semaphore with initial resources available.

Throws: os_thread_toolkit_error

Constructor
os_counting_semaphore( unsigned int initial , unsigned int maximum )
Constructs a counting semaphore with initial resources available and a maximum size.

Throws: os_thread_toolkit_error

Destructor
~os_counting_semaphore()
Destroys this semaphore.
count
unsigned int count() const
Returns the current count.

Throws: os_thread_toolkit_error

lock
void lock( unsigned int count )
Decrements the number of resources by count (default 1 ). If no resources are present, blocks until one becomes available.

Throws: os_thread_toolkit_error

obtain
void obtain( unsigned int count )
Synonym for lock() ; alternative acquisition syntax.

Throws: os_thread_toolkit_error

post
void post( unsigned int count )
Synonym for unlock() ; alternative event syntax.

Throws: os_thread_toolkit_error

print
void print( ostream& stream ) const
Prints to stream .

Throws: os_thread_toolkit_error

release
void release( unsigned int count )
Synonym for unlock() ; alternative acquisition syntax.

Throws: os_thread_toolkit_error

size
unsigned int size() const
Returns size.

Throws: os_thread_toolkit_error

try_lock
bool try_lock( unsigned int count )
If the counting semaphore has at least count resources, decrements the resources by count (default 1 ) and returns true ; otherwise, leaves the resource count unchanged and immediately returns false .

Throws: os_thread_toolkit_error

unlock
void unlock( unsigned int count )
Increments the number of resources by count (default 1 ).

Throws: os_thread_toolkit_error

wait
void wait( unsigned int count )
Synonym for lock() ; alternative event syntax.

Throws: os_thread_toolkit_error

Non-Member Functions

<<
ostream& operator<<( ostream& stream , const os_counting_semaphore& semaphore )
Prints semaphore to stream .

Throws: os_thread_toolkit_error


Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.