SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
stk_sync_semaphore.h
Go to the documentation of this file.
1/*
2 * SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
3 *
4 * Source: https://github.com/SuperTinyKernel-RTOS
5 *
6 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
7 * License: MIT License, see LICENSE for a full text.
8 */
9
10#ifndef STK_SYNC_SEMAPHORE_H_
11#define STK_SYNC_SEMAPHORE_H_
12
13#include "stk_sync_cs.h"
14
18
19namespace stk {
20namespace sync {
21
70template <typename T>
71class SemaphoreT final : public SyncObjectBase, public ITraceable
72{
73 STK_STATIC_ASSERT_DESC(static_cast<T>(-1) > static_cast<T>(0), "SemaphoreT: T must be an unsigned integer type");
74
75public:
79
82 static constexpr T COUNT_MAX = static_cast<T>(~static_cast<T>(0U));
83
93 explicit SemaphoreT(T initial_count = 0U, T max_count = COUNT_MAX)
94 : m_count(initial_count), m_count_max(max_count)
95 {
96 STK_ASSERT(initial_count <= max_count); // API contract: initial count must not exceed maximum
97 }
98
106 {
107 STK_ASSERT(m_wait_list.IsEmpty()); // API contract: must not be destroyed with waiting tasks
108 }
109
120
127 bool Wait(Timeout timeout_ticks = WAIT_INFINITE) { return (WaitEx(timeout_ticks) == WAIT_RESULT_SIGNAL); }
128
136 bool TryWait() { return Wait(NO_WAIT); }
137
147 void Signal();
148
160 bool TrySignal();
161
174 bool TrySignal(const T ceiling);
175
184 T GetCount() const { return ReadCount(ReadTag<(sizeof(T) > sizeof(void *))>()); }
185
186private:
188
190 template <bool WIDE> struct ReadTag {};
191
193 __stk_forceinline T ReadCount(ReadTag<false>) const { return m_count; }
194
196 __stk_forceinline T ReadCount(ReadTag<true>) const
197 {
198 const ScopedCriticalSection cs_;
199 return m_count;
200 }
201
206 bool TrySignalLimited(const T limit);
207
210};
211
212#if (__cplusplus < 201703L)
213// out-of-class definition, required before C++17 if COUNT_MAX is ODR-used (e.g. bound to a const reference);
214// since C++17 static constexpr data members are implicitly inline and this definition is redundant (deprecated)
215template <typename T>
217#endif
218
224
225// ---------------------------------------------------------------------------
226// Wait
227// ---------------------------------------------------------------------------
228
229template <typename T>
231{
232 // guard
234
235 // NO_WAIT with no token available is reported as an immediately-expired timeout
237
238 // fast path: resource is available
239 if (m_count != 0U)
240 {
241 m_count = static_cast<T>(m_count - 1U);
242 result = WAIT_RESULT_SIGNAL;
243 }
244 // slow path: block until Signal() or timeout
245 else if (timeout_ticks != NO_WAIT)
246 {
247 STK_ASSERT(!hw::IsInsideISR()); // API contract: caller must not be in ISR if timeout_ticks!=NO_WAIT
248
249 // note: after waking, if not a timeout, we effectively own the resource that Signal() produced
250 // but didn't put into m_count (see logic of if (m_wait_list.IsEmpty()) in TrySignalLimited())
251 result = IKernelService::GetInstance()->Wait(this, &cs_, timeout_ticks);
252 }
253 // try lock behavior (timeout_ticks=NO_WAIT)
254 else
255 {
256 // result is WAIT_RESULT_TIMEOUT already, noop
257 }
258
259 return result;
260}
261
262// ---------------------------------------------------------------------------
263// Signal
264// ---------------------------------------------------------------------------
265
266template <typename T>
268{
269 const bool success = TrySignal();
270 STK_UNUSED(success);
271 STK_ASSERT(success); // API contract: the count must not exceed maximum
272}
273
274// ---------------------------------------------------------------------------
275// TrySignal
276// ---------------------------------------------------------------------------
277
278template <typename T>
280{
282}
283
284template <typename T>
285inline bool SemaphoreT<T>::TrySignal(const T ceiling)
286{
287 // effective limit is the smaller of the per-call ceiling and the per-object maximum
288 return TrySignalLimited((ceiling < m_count_max) ? ceiling : m_count_max);
289}
290
291template <typename T>
292inline bool SemaphoreT<T>::TrySignalLimited(const T limit)
293{
294 bool success = true;
295
296 // guard
297 const ScopedCriticalSection cs_;
298
299 if (m_wait_list.IsEmpty())
300 {
301 if (m_count >= limit)
302 {
303 // counter already saturated and no one is waiting to hand the token to directly
304 success = false;
305 }
306 else
307 {
308 // no one is waiting, save signal for later
309 m_count = static_cast<T>(m_count + 1U);
310 }
311 }
312 else
313 {
314 // give signal directly to the first waiting task
315 WakeOne();
316 }
317
318 return success;
319}
320
321} // namespace sync
322} // namespace stk
323
324#endif /* STK_SYNC_SEMAPHORE_H_ */
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define __stk_forceinline
Forces compiler to always inline the decorated function, regardless of optimisation level.
Definition stk_defs.h:270
#define STK_NONCOPYABLE_CLASS(TYPE)
Deletes (= delete) the copy constructor and copy assignment operator of a class.
Definition stk_defs.h:708
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
#define STK_STATIC_ASSERT_DESC(X, DESC)
Compile-time assertion with a custom error description. Produces a compilation error if X is false.
Definition stk_defs.h:548
#define STK_VIRT_DTOR
Expands to nothing if STK_STRICT_COMPLIANCY=0 (non-virtual destructors, smaller objects),...
Definition stk_defs.h:254
Implementation of synchronization primitive: stk::sync::ScopedCriticalSection.
Namespace of STK package.
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:280
EWaitResult
Wait result (see IKernelService::Wait).
Definition stk_common.h:138
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:141
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:140
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:216
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
Synchronization primitives for task coordination and resource protection.
SemaphoreT< uint16_t > Semaphore
Default counting semaphore with a 16-bit counter (max count 0xFFFF).
Traceable object.
Definition stk_common.h:606
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout)=0
Put calling process into a waiting state until synchronization object is signaled or timeout occurs.
SyncObjectBase()
Constructor.
Definition stk_helper.h:274
IWaitObject::ListHeadType m_wait_list
Definition stk_helper.h:311
void WakeOne() override
Wake the first task in the wait list (FIFO order).
Definition stk_helper.h:296
RAII-style low-level synchronization primitive for atomic code execution. Used as building brick for ...
Definition stk_sync_cs.h:58
Counting semaphore primitive for resource management and signaling, with a selectable counter type.
static constexpr uint16_t COUNT_MAX
bool TrySignalLimited(const T limit)
Common signal path: hand off to a waiter or increment up to limit.
T CounterValueType
Counter value type.
T GetCount() const
Get current counter value.
T ReadCount(ReadTag< false >) const
Counter fits the native word: a single load is atomic.
bool Wait(Timeout timeout_ticks=WAIT_INFINITE)
Wait for a signal (decrement counter).
bool TrySignal()
Try to post a signal without exceeding max_count.
T ReadCount(ReadTag< true >) const
Counter is wider than the native word: a plain load may be split into several, guard it.
bool TrySignal(const T ceiling)
Try to post a signal without exceeding a caller-supplied ceiling.
void Signal()
Post a signal (increment counter).
bool TryWait()
Poll the semaphore without blocking (decrement counter if available).
EWaitResult WaitEx(Timeout timeout_ticks=WAIT_INFINITE)
Wait for a signal (decrement counter), preserving the full wait outcome.
SemaphoreT(T initial_count=0U, T max_count=COUNT_MAX)
Constructor.
Selects how the counter is read: WIDE is true if T is wider than a pointer.