Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
SC::Semaphore Struct Reference

A semaphore synchronization primitive that maintains a count for resource management. More...

#include <Threading.h>

Public Member Functions

 Semaphore (int initialCount=0)
 Creates a semaphore with an initial count.
 
void acquire ()
 Wait for a resource to become available.
 
void release ()
 Make a resource available.
 

Detailed Description

A semaphore synchronization primitive that maintains a count for resource management.

Example:

constexpr int maxResources = 2; // Only 2 threads can access resource at once
constexpr int numThreads = 4; // Total number of threads trying to access
constexpr int operationsPerThread = 3; // Each thread will do 3 operations
Semaphore semaphore(maxResources); // Initialize with 2 available resources
struct Context
{
Semaphore& semaphore;
Mutex counterMutex; // To protect sharedResource counter
int sharedResource = 0; // Counter to verify correct synchronization
} ctx{semaphore, {}};
Thread threads[numThreads];
for (int i = 0; i < numThreads; i++)
{
auto threadFunc = [this, &ctx](Thread& thread)
{
thread.setThreadName(SC_NATIVE_STR("Worker Thread"));
for (int j = 0; j < operationsPerThread; j++)
{
ctx.semaphore.acquire(); // Wait for resource to be available
// Critical section
ctx.counterMutex.lock();
ctx.sharedResource++;
SC_TEST_EXPECT(ctx.sharedResource <= maxResources); // Never more than maxResources threads
Thread::Sleep(1); // Simulate some work
ctx.sharedResource--;
ctx.counterMutex.unlock();
ctx.semaphore.release(); // Release the resource
Thread::Sleep(1); // Give other threads a chance
}
};
SC_TEST_EXPECT(threads[i].start(threadFunc));
}
// Wait for all threads to finish
for (int i = 0; i < numThreads; i++)
{
SC_TEST_EXPECT(threads[i].join());
}
// Verify final state
SC_TEST_EXPECT(ctx.sharedResource == 0);

Constructor & Destructor Documentation

◆ Semaphore()

SC::Semaphore::Semaphore ( int initialCount = 0)

Creates a semaphore with an initial count.

Parameters
initialCountThe initial number of resources available

Member Function Documentation

◆ acquire()

void SC::Semaphore::acquire ( )

Wait for a resource to become available.

◆ release()

void SC::Semaphore::release ( )

Make a resource available.


The documentation for this struct was generated from the following file: