SuperTinyKernel™ RTOS 1.06.0
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
stk::sync::Semaphore Class Reference

Counting semaphore primitive for resource management and signaling. More...

#include <stk_sync_semaphore.h>

Inheritance diagram for stk::sync::Semaphore:
Collaboration diagram for stk::sync::Semaphore:

Public Member Functions

 Semaphore (uint16_t initial_count=0U, uint16_t max_count=COUNT_MAX)
 Constructor.
 ~Semaphore ()
 Destructor.
bool Wait (Timeout timeout=WAIT_INFINITE)
 Wait for a signal (decrement counter).
bool TryWait ()
 Poll the semaphore without blocking (decrement counter if available).
void Signal ()
 Post a signal (increment counter).
uint16_t GetCount () const
 Get current counter value.
void SetTraceName (const char *name)
 Set name.
const char * GetTraceName () const
 Get name.

Static Public Attributes

static const size_t COUNT_MAX = 0xFFFEU
 Max count supported.

Private Types

typedef DLHeadType ListHeadType
 List head type for ISyncObject elements.
typedef DLEntryType ListEntryType
 List entry type of ISyncObject elements.
typedef DListEntry< ISyncObject, _ClosedLoop > DLEntryType
 Convenience alias for this entry type. Used to avoid repeating the full template spelling.
typedef DListHead< ISyncObject, _ClosedLoop > DLHeadType
 Convenience alias for the corresponding list head type.

Private Member Functions

 STK_NONCOPYABLE_CLASS (Semaphore)
virtual void AddWaitObject (IWaitObject *wobj)
 Called by kernel when a new task starts waiting on this event.
virtual void RemoveWaitObject (IWaitObject *wobj)
 Called by kernel when a waiting task is being removed (timeout expired, wait aborted, task terminated etc.).
virtual bool Tick (Timeout elapsed_ticks)
 Called by kernel on every system tick to handle timeout logic of waiting tasks.
void WakeOne ()
 Wake the first task in the wait list (FIFO order).
void WakeAll ()
 Wake all tasks currently in the wait list.
DLHeadTypeGetHead () const
 Get the list head this entry currently belongs to.
DLEntryTypeGetNext () const
 Get the next entry in the list.
DLEntryTypeGetPrev () const
 Get the previous entry in the list.
bool IsLinked () const
 Check whether this entry is currently a member of any list.
 operator ISyncObject * ()
 Implicit conversion to a mutable pointer to the host object (T).
 operator const ISyncObject * () const
 Implicit conversion to a const pointer to the host object (T).
void Link (DLHeadType *head, DLEntryType *next, DLEntryType *prev)
 Wire this entry into a list between prev and next.
void Unlink ()
 Remove this entry from its current list.

Private Attributes

uint16_t m_count
 Internal resource counter.
uint16_t m_count_max
 Counter max limit.
IWaitObject::ListHeadType m_wait_list
 tasks blocked on this object
DLHeadTypem_head
 Owning list head, or NULL when the entry is not linked.
DLEntryTypem_next
 Next entry in the list, or NULL (open list boundary) / first entry (closed loop).
DLEntryTypem_prev
 Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

Detailed Description

Counting semaphore primitive for resource management and signaling.

Counting semaphore maintains an internal counter to manage access to a limited number of resources. Unlike a Condition Variable, a Semaphore is stateful: if Signal() is called when no tasks are waiting, the signal is "remembered" by incrementing the internal counter.

Note
This implementation uses a Direct Handover policy: when a task is waiting, Signal() gives the resource "token" directly to the first task in the wait list without incrementing the counter. The waking task is then guaranteed ownership of that token upon returning from Wait().
// Example: Resource throttling
// Initialize with 3 permits (e.g., max 3 concurrent tasks accessing the same resource)
stk::sync::Semaphore g_Limiter(3);
void Worker() {
// attempt to acquire a permit with a 1000 tick timeout
if (g_Limiter.Wait(1000)) {
// ... access limited resource ...
// release the permit back to the semaphore
g_Limiter.Signal();
}
}
Counting semaphore primitive for resource management and signaling.
See also
ISyncObject, IWaitObject, IKernelService::Wait
Note
Only available when kernel is compiled with KERNEL_SYNC mode enabled.

Definition at line 55 of file stk_sync_semaphore.h.

Member Typedef Documentation

◆ DLEntryType

typedef DListEntry<ISyncObject, _ClosedLoop> stk::util::DListEntry< ISyncObject, _ClosedLoop >::DLEntryType
inherited

Convenience alias for this entry type. Used to avoid repeating the full template spelling.

Definition at line 70 of file stk_linked_list.h.

◆ DLHeadType

typedef DListHead<ISyncObject, _ClosedLoop> stk::util::DListEntry< ISyncObject, _ClosedLoop >::DLHeadType
inherited

Convenience alias for the corresponding list head type.

Definition at line 75 of file stk_linked_list.h.

◆ ListEntryType

List entry type of ISyncObject elements.

Definition at line 371 of file stk_common.h.

◆ ListHeadType

List head type for ISyncObject elements.

Definition at line 366 of file stk_common.h.

Constructor & Destructor Documentation

◆ Semaphore()

stk::sync::Semaphore::Semaphore ( uint16_t initial_count = 0U,
uint16_t max_count = COUNT_MAX )
inlineexplicit

Constructor.

Parameters
[in]initial_countStarting value of the semaphore.

Definition at line 65 of file stk_sync_semaphore.h.

66 : m_count(initial_count), m_count_max(max_count)
67 {
68 STK_ASSERT(initial_count < max_count); // API contract: initial count must not exceed maximum
69 }
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:330
uint16_t m_count_max
Counter max limit.
uint16_t m_count
Internal resource counter.

References COUNT_MAX, m_count, m_count_max, and STK_ASSERT.

Referenced by STK_NONCOPYABLE_CLASS().

Here is the caller graph for this function:

◆ ~Semaphore()

stk::sync::Semaphore::~Semaphore ( )
inline

Destructor.

Note
If tasks are still waiting at destruction time it is considered a logical error (dangling waiters). An assertion is triggered in debug builds.
MISRA deviation: [STK-DEV-005] Rule 10-3-2.

Definition at line 77 of file stk_sync_semaphore.h.

78 {
79 STK_ASSERT(m_wait_list.IsEmpty()); // API contract: must not be destroyed with waiting tasks
80 }
IWaitObject::ListHeadType m_wait_list
tasks blocked on this object
Definition stk_common.h:431

References stk::ISyncObject::m_wait_list, and STK_ASSERT.

Member Function Documentation

◆ AddWaitObject()

virtual void stk::ISyncObject::AddWaitObject ( IWaitObject * wobj)
inlinevirtualinherited

Called by kernel when a new task starts waiting on this event.

Parameters
[in]wobjWait object representing blocked task.

Definition at line 376 of file stk_common.h.

377 {
378 STK_ASSERT(wobj->GetHead() == nullptr);
379 m_wait_list.LinkBack(wobj);
380 }

References stk::util::DListEntry< T, _ClosedLoop >::GetHead(), m_wait_list, and STK_ASSERT.

Referenced by stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::WaitObject::SetupWait().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetCount()

uint16_t stk::sync::Semaphore::GetCount ( ) const
inline

Get current counter value.

Returns
Advisory snapshot of the counter. May be stale by the time the caller acts on it. Atomic on 32-bit aligned targets.
Note
ISR-safe on targets where a 32-bit aligned read is a single instruction (all supported STK architectures). Not safe for read-modify-write use.

Definition at line 111 of file stk_sync_semaphore.h.

111{ return m_count; }

References m_count.

Referenced by osSemaphoreGetCount().

Here is the caller graph for this function:

◆ GetHead()

DLHeadType * stk::util::DListEntry< ISyncObject, _ClosedLoop >::GetHead ( ) const
inlineinherited

Get the list head this entry currently belongs to.

Returns
Pointer to the owning DListHead, or NULL if the entry is not linked.

Definition at line 80 of file stk_linked_list.h.

80{ return m_head; }
Intrusive doubly-linked list node. Embed this as a base class in any object (T) that needs to partici...

◆ GetNext()

DLEntryType * stk::util::DListEntry< ISyncObject, _ClosedLoop >::GetNext ( ) const
inlineinherited

Get the next entry in the list.

Returns
Pointer to the next DListEntry, or NULL if this is the last entry (open list) or the first entry (closed loop, where next wraps to first).
Note
In a closed loop (_ClosedLoop == true) this pointer is never NULL when the entry is linked.

Definition at line 88 of file stk_linked_list.h.

88{ return m_next; }

◆ GetPrev()

DLEntryType * stk::util::DListEntry< ISyncObject, _ClosedLoop >::GetPrev ( ) const
inlineinherited

Get the previous entry in the list.

Returns
Pointer to the previous DListEntry, or NULL if this is the first entry (open list) or the last entry (closed loop, where prev wraps to last).
Note
In a closed loop (_ClosedLoop == true) this pointer is never NULL when the entry is linked.

Definition at line 96 of file stk_linked_list.h.

96{ return m_prev; }

◆ GetTraceName()

const char * stk::ITraceable::GetTraceName ( ) const
inlineinherited

Get name.

Returns
Name string, or NULL if not set or if STK_SYNC_DEBUG_NAMES is 0.

Definition at line 336 of file stk_common.h.

337 {
338 #if STK_SYNC_DEBUG_NAMES
339 return m_trace_name;
340 #else
341 return nullptr;
342 #endif
343 }

◆ IsLinked()

bool stk::util::DListEntry< ISyncObject, _ClosedLoop >::IsLinked ( ) const
inlineinherited

Check whether this entry is currently a member of any list.

Returns
true if linked (m_head != NULL); false otherwise.

Definition at line 101 of file stk_linked_list.h.

101{ return (GetHead() != nullptr); }

◆ Link()

void stk::util::DListEntry< ISyncObject, _ClosedLoop >::Link ( DLHeadType * head,
DLEntryType * next,
DLEntryType * prev )
inlineprivateinherited

Wire this entry into a list between prev and next.

Parameters
[in]headThe owning DListHead. Stored as a back-pointer for IsLinked() and ownership checks.
[in]nextThe entry that will follow this one, or NULL if this becomes the last entry.
[in]prevThe entry that will precede this one, or NULL if this becomes the first entry.
Note
Called exclusively by DListHead::Link(). Assumes the entry is not currently linked. Updates the neighbours' forward/back pointers to splice this entry in.

Definition at line 137 of file stk_linked_list.h.

138 {
139 m_head = head;
140 m_next = next;
141 m_prev = prev;
142
143 if (m_prev != nullptr)
144 m_prev->m_next = this;
145
146 if (m_next != nullptr)
147 m_next->m_prev = this;
148 }
DLEntryType * m_next
Next entry in the list, or NULL (open list boundary) / first entry (closed loop).
DLEntryType * m_prev
Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

◆ operator const ISyncObject *()

stk::util::DListEntry< ISyncObject, _ClosedLoop >::operator const ISyncObject * ( ) const
inlineinherited

Implicit conversion to a const pointer to the host object (T).

Note
Safe because T must derive from DListEntry<T, _ClosedLoop>. Eliminates the need for explicit static_cast at call sites.
MISRA deviation: [STK-DEV-004] Rule 5-2-x.

Definition at line 115 of file stk_linked_list.h.

115{ return static_cast<const T *>(this); }

◆ operator ISyncObject *()

stk::util::DListEntry< ISyncObject, _ClosedLoop >::operator ISyncObject* ( )
inlineinherited

Implicit conversion to a mutable pointer to the host object (T).

Note
Safe because T must derive from DListEntry<T, _ClosedLoop>. Eliminates the need for explicit static_cast at call sites.
MISRA deviation: [STK-DEV-004] Rule 5-2-x.

Definition at line 108 of file stk_linked_list.h.

108{ return static_cast<T *>(this); }

◆ RemoveWaitObject()

virtual void stk::ISyncObject::RemoveWaitObject ( IWaitObject * wobj)
inlinevirtualinherited

Called by kernel when a waiting task is being removed (timeout expired, wait aborted, task terminated etc.).

Parameters
[in]wobjWait object to remove from the wait list.

Reimplemented in stk::sync::Event.

Definition at line 385 of file stk_common.h.

386 {
387 STK_ASSERT(wobj->GetHead() == &m_wait_list);
388 m_wait_list.Unlink(wobj);
389 }

References stk::util::DListEntry< T, _ClosedLoop >::GetHead(), m_wait_list, and STK_ASSERT.

Referenced by stk::sync::Event::RemoveWaitObject().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetTraceName()

void stk::ITraceable::SetTraceName ( const char * name)
inlineinherited

Set name.

Parameters
[in]nameNull-terminated string or NULL.
Note
If STK_SYNC_DEBUG_NAMES is 0 then calling this function has no effect.

Definition at line 324 of file stk_common.h.

325 {
326 #if STK_SYNC_DEBUG_NAMES
327 m_trace_name = name;
328 #else
329 STK_UNUSED(name);
330 #endif
331 }
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:524

References STK_UNUSED.

◆ Signal()

void stk::sync::Semaphore::Signal ( )
inline

Post a signal (increment counter).

Note
Gives "token" directly to the waking task. The count is not incremented, and the waking task does not decrement it.
ISR-safe.

Definition at line 152 of file stk_sync_semaphore.h.

153{
154 ScopedCriticalSection cs_;
155
156 if (m_wait_list.IsEmpty())
157 {
158 STK_ASSERT(m_count < m_count_max); // API contract: the count must not exceed maximum
159
160 // no one is waiting, save signal for later
161 m_count = static_cast<uint16_t>(m_count + 1U);
162 __stk_full_memfence();
163 }
164 else
165 {
166 // give signal directly to the first waiting task
167 WakeOne();
168 }
169}
void WakeOne()
Wake the first task in the wait list (FIFO order).
Definition stk_common.h:415

References m_count, m_count_max, stk::ISyncObject::m_wait_list, STK_ASSERT, and stk::ISyncObject::WakeOne().

Referenced by stk_sem_signal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ STK_NONCOPYABLE_CLASS()

stk::sync::Semaphore::STK_NONCOPYABLE_CLASS ( Semaphore )
private

References Semaphore().

Here is the call graph for this function:

◆ Tick()

bool stk::ISyncObject::Tick ( Timeout elapsed_ticks)
inlinevirtualinherited

Called by kernel on every system tick to handle timeout logic of waiting tasks.

Implementation of ISyncObject::Tick, see ISyncObject. Placed here as it depends on hw namespace.

Parameters
[in]elapsed_ticksNumber of ticks elapsed between this and previous calls, in case of KERNEL_TICKLESS mode this value can be >1, for non-tickless mode it is always 1.
Returns
true if this synchronization object still has waiters with a finite timeout and requires further tick calls. false if the wait list is empty or all remaining waiters have infinite timeouts, signaling to the kernel that it may stop calling Tick() for this object until a new waiter is added.
Note
When this method returns false, the kernel unlinks this object from its active sync list. It will be re-linked automatically when the next waiter is added via AddWaitObject().

Definition at line 467 of file stk_arch.h.

468{
469 // note: ScopedCriticalSection usage
470 //
471 // Single-core: no critical section needed - Tick() runs inside the
472 // SysTick ISR which already executes with interrupts disabled, making
473 // re-entrancy impossible on the local core.
474 //
475 // Multi-core: critical section is required because the tick handler on
476 // each core may call Tick() concurrently for the same Semaphore instance,
477 // and ISyncObject::Tick() is not re-entrant.
478#if (STK_ARCH_CPU_COUNT > 1)
479 hw::CriticalSection::ScopedLock cs_;
480#endif
481
482 IWaitObject *itr = static_cast<IWaitObject *>(m_wait_list.GetFirst());
483
484 while (itr != nullptr)
485 {
486 IWaitObject *next = static_cast<IWaitObject *>(itr->GetNext());
487
488 if (!itr->Tick(elapsed_ticks))
489 itr->Wake(true);
490
491 itr = next;
492 }
493
494 return !m_wait_list.IsEmpty();
495}

References stk::util::DListEntry< T, _ClosedLoop >::GetNext(), m_wait_list, stk::IWaitObject::Tick(), and stk::IWaitObject::Wake().

Here is the call graph for this function:

◆ TryWait()

bool stk::sync::Semaphore::TryWait ( )
inline

Poll the semaphore without blocking (decrement counter if available).

Checks if a resource token is available. If so, decrements the counter and returns immediately without yielding the CPU or touching the kernel wait list. If the counter is zero, returns immediately with false.

Note
ISR-safe.
Returns
true if a resource token was acquired, false if count was zero.

Definition at line 96 of file stk_sync_semaphore.h.

96{ return Wait(NO_WAIT); }
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:177
bool Wait(Timeout timeout=WAIT_INFINITE)
Wait for a signal (decrement counter).

References stk::NO_WAIT, and Wait().

Here is the call graph for this function:

◆ Unlink()

void stk::util::DListEntry< ISyncObject, _ClosedLoop >::Unlink ( )
inlineprivateinherited

Remove this entry from its current list.

Note
Called exclusively by DListHead::Unlink(). Patches the neighbours' pointers to bridge over this entry, then clears m_head, m_next, and m_prev to NULL so the entry is in a clean unlinked state.
Does not update DListHead::m_count or m_first / m_last — those are the responsibility of the calling DListHead::Unlink().

Definition at line 157 of file stk_linked_list.h.

158 {
159 if (m_prev != nullptr)
161
162 if (m_next != nullptr)
164
165 m_head = nullptr;
166 m_next = nullptr;
167 m_prev = nullptr;
168 }

◆ Wait()

bool stk::sync::Semaphore::Wait ( Timeout timeout = WAIT_INFINITE)
inline

Wait for a signal (decrement counter).

Parameters
[in]timeoutMaximum time to wait (ticks).
Warning
ISR-safe only with timeout = NO_WAIT, ISR-unsafe otherwise.
Returns
True if acquired, false if timeout occurred.

Definition at line 124 of file stk_sync_semaphore.h.

125{
126 ScopedCriticalSection cs_;
127
128 // fast path: resource is available
129 if (m_count != 0U)
130 {
131 m_count = static_cast<uint16_t>(m_count - 1U);
132 __stk_full_memfence();
133 return true;
134 }
135
136 // try lock behavior (timeout=NO_WAIT)
137 if (timeout == NO_WAIT)
138 return false;
139
140 STK_ASSERT(!hw::IsInsideISR()); // API contract: caller must not be in ISR if timeout!=NO_WAIT
141
142 // slow path: block until Signal() or timeout
143 // note: after waking, if not a timeout, we effectively own the resource that Signal() produced
144 // but didn't put into m_count (see logic of if (m_wait_list.IsEmpty()) in Signal())
145 return !IKernelService::GetInstance()->Wait(this, &cs_, timeout)->IsTimeout();
146}
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
virtual bool IsTimeout() const =0
Check if task woke up due to a timeout.
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
virtual IWaitObject * Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout)=0
Put calling process into a waiting state until synchronization object is signaled or timeout occurs.

References stk::IKernelService::GetInstance(), stk::hw::IsInsideISR(), stk::IWaitObject::IsTimeout(), m_count, stk::NO_WAIT, STK_ASSERT, and stk::IKernelService::Wait().

Referenced by osSemaphoreAcquire(), stk_sem_wait(), and TryWait().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ WakeAll()

void stk::ISyncObject::WakeAll ( )
inlineprotectedinherited

Wake all tasks currently in the wait list.

Note
Each woken task is notified with timeout=false, indicating a successful signal (not a timeout expiry).
Does nothing if no tasks are currently waiting.

Definition at line 425 of file stk_common.h.

426 {
427 while (!m_wait_list.IsEmpty())
428 static_cast<IWaitObject *>(m_wait_list.GetFirst())->Wake(false);
429 }

References m_wait_list, and stk::IWaitObject::Wake().

Referenced by stk::sync::ConditionVariable::NotifyAll_CS(), stk::sync::Event::Pulse(), and stk::sync::Event::Set().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ WakeOne()

void stk::ISyncObject::WakeOne ( )
inlineprotectedinherited

Wake the first task in the wait list (FIFO order).

Note
The woken task is notified with timeout=false, indicating a successful signal (not a timeout expiry).
Does nothing if no tasks are currently waiting.

Definition at line 415 of file stk_common.h.

416 {
417 if (!m_wait_list.IsEmpty())
418 static_cast<IWaitObject *>(m_wait_list.GetFirst())->Wake(false);
419 }

References m_wait_list, and stk::IWaitObject::Wake().

Referenced by stk::sync::ConditionVariable::NotifyOne_CS(), stk::sync::Event::Pulse(), stk::sync::Event::Set(), and stk::sync::Semaphore::Signal().

Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ COUNT_MAX

const size_t stk::sync::Semaphore::COUNT_MAX = 0xFFFEU
static

Max count supported.

Definition at line 60 of file stk_sync_semaphore.h.

Referenced by osSemaphoreNew(), and Semaphore().

◆ m_count

uint16_t stk::sync::Semaphore::m_count
private

Internal resource counter.

Definition at line 116 of file stk_sync_semaphore.h.

Referenced by GetCount(), Semaphore(), Signal(), and Wait().

◆ m_count_max

uint16_t stk::sync::Semaphore::m_count_max
private

Counter max limit.

Definition at line 117 of file stk_sync_semaphore.h.

Referenced by Semaphore(), and Signal().

◆ m_head

DLHeadType* stk::util::DListEntry< ISyncObject, _ClosedLoop >::m_head
privateinherited

Owning list head, or NULL when the entry is not linked.

Definition at line 170 of file stk_linked_list.h.

◆ m_next

DLEntryType* stk::util::DListEntry< ISyncObject, _ClosedLoop >::m_next
privateinherited

Next entry in the list, or NULL (open list boundary) / first entry (closed loop).

Definition at line 171 of file stk_linked_list.h.

◆ m_prev

DLEntryType* stk::util::DListEntry< ISyncObject, _ClosedLoop >::m_prev
privateinherited

Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

Definition at line 172 of file stk_linked_list.h.

◆ m_wait_list


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