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_eventflags.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_EVENT_FLAGS_H_
11#define STK_SYNC_EVENT_FLAGS_H_
12
13#include "stk_sync_cv.h"
14
18
19namespace stk {
20namespace sync {
21
99template <typename T>
100class EventFlagsT final : public ITraceable
101{
102 STK_STATIC_ASSERT_DESC(static_cast<T>(-1) > static_cast<T>(0), "EventFlagsT: T must be an unsigned integer type");
103
104public:
107 typedef T FlagsValueType;
108
109 // -----------------------------------------------------------------------
110 // Word constants
111 // -----------------------------------------------------------------------
112
115 static constexpr T FLAGS_MAX = static_cast<T>(~static_cast<T>(0U));
116
120 static constexpr T ERROR_MASK = static_cast<T>(~static_cast<T>(FLAGS_MAX >> 1U));
121
124 static constexpr T FLAGS_MASK = static_cast<T>(~ERROR_MASK);
125
126 // -----------------------------------------------------------------------
127 // Options constants (bitmask, passed to Wait())
128 // -----------------------------------------------------------------------
129
131 static constexpr uint32_t OPT_WAIT_ANY = 0x00000000U;
132
134 static constexpr uint32_t OPT_WAIT_ALL = 0x00000001U;
135
137 static constexpr uint32_t OPT_NO_CLEAR = 0x00000002U;
138
139 // -----------------------------------------------------------------------
140 // Return-value error sentinels (the most significant bit of T is the error indicator)
141 // -----------------------------------------------------------------------
142
144 static constexpr T ERROR_PARAMETER = static_cast<T>(ERROR_MASK | static_cast<T>(0x01U));
145
147 static constexpr T ERROR_TIMEOUT = static_cast<T>(ERROR_MASK | static_cast<T>(0x02U));
148
150 static constexpr T ERROR_ISR = static_cast<T>(ERROR_MASK | static_cast<T>(0x04U));
151
154 static constexpr T ERROR_CANCELED = static_cast<T>(ERROR_MASK | static_cast<T>(0x08U));
155
158 static constexpr T ERROR_FAIL = static_cast<T>(ERROR_MASK | static_cast<T>(0x10U));
159
160 // -----------------------------------------------------------------------
161 // Validation helpers
162 // -----------------------------------------------------------------------
163
167 static bool IsError(T result) { return ((result & ERROR_MASK) != 0U); }
168
169 // -----------------------------------------------------------------------
170 // Construction / destruction
171 // -----------------------------------------------------------------------
172
177 explicit EventFlagsT(T initial_flags = 0U) : m_flags(initial_flags)
178 {
179 STK_ASSERT((initial_flags & ERROR_MASK) == 0U); // API contract: the reserved bit must not be set
180 }
181
188
189 // -----------------------------------------------------------------------
190 // Flag manipulation
191 // -----------------------------------------------------------------------
192
202 T Set(T flags);
203
211 T Clear(T flags);
212
225 T And(T mask);
226
236 T Get() const { return ReadFlags(ReadTag<(sizeof(T) > sizeof(void *))>()); }
237
238 // -----------------------------------------------------------------------
239 // Waiting
240 // -----------------------------------------------------------------------
241
267 T Wait(T flags, uint32_t options = OPT_WAIT_ANY, Timeout timeout_ticks = WAIT_INFINITE);
268
289 EWaitResult WaitEx(T flags, uint32_t options, Timeout timeout_ticks, T &actual_flags);
290
298 EWaitResult TryWaitEx(T flags, uint32_t options, T &actual_flags)
299 {
300 return WaitEx(flags, options, NO_WAIT, actual_flags);
301 }
302
313 {
315 {}
316
317 uint32_t m_gen;
319 };
320
347 EWaitResult Sync(SyncContext &ctx, T set_flags, T wait_flags, Timeout timeout_ticks, T &actual_flags);
348
357 T TryWait(T flags, uint32_t options = OPT_WAIT_ANY)
358 {
359 return Wait(flags, options, NO_WAIT);
360 }
361
368 {
369 return m_cv.GetWaitList();
370 }
371
381 {
382 return m_cv.GetFirstWaiterTid();
383 }
384
385private:
387
389 template <bool WIDE> struct ReadTag {};
390
392 __stk_forceinline T ReadFlags(ReadTag<false>) const { return m_flags; }
393
395 __stk_forceinline T ReadFlags(ReadTag<true>) const
396 {
398 return m_flags;
399 }
400
401 // Predicate: returns true when the wait condition for 'flags'/'options' is met.
402 // Must be called inside the critical section.
403 bool IsSatisfied(T flags, uint32_t options) const
404 {
405 return ((options & OPT_WAIT_ALL) == OPT_WAIT_ALL) ? ((m_flags & flags) == flags) :
406 ((m_flags & flags) != 0U);
407 }
408
409 // Core wait loop shared by Wait() and WaitEx() (arguments must already be validated).
410 // Returns WAIT_RESULT_SIGNAL when the predicate was satisfied, otherwise the failing result.
411 // actual_flags receives the whole flags word before auto-clear.
412 EWaitResult WaitCore(T flags, uint32_t options, Timeout timeout_ticks, T &actual_flags);
413
414 volatile T m_flags;
416};
417
418#if (__cplusplus < 201703L)
419// out-of-class definitions, required before C++17 if a constant is ODR-used (e.g. bound to a const
420// reference); since C++17 static constexpr data members are implicitly inline and these definitions
421// are redundant (deprecated)
422template <typename T> constexpr T EventFlagsT<T>::FLAGS_MAX;
423template <typename T> constexpr T EventFlagsT<T>::ERROR_MASK;
424template <typename T> constexpr T EventFlagsT<T>::FLAGS_MASK;
425template <typename T> constexpr uint32_t EventFlagsT<T>::OPT_WAIT_ANY;
426template <typename T> constexpr uint32_t EventFlagsT<T>::OPT_WAIT_ALL;
427template <typename T> constexpr uint32_t EventFlagsT<T>::OPT_NO_CLEAR;
428template <typename T> constexpr T EventFlagsT<T>::ERROR_PARAMETER;
429template <typename T> constexpr T EventFlagsT<T>::ERROR_TIMEOUT;
430template <typename T> constexpr T EventFlagsT<T>::ERROR_ISR;
431template <typename T> constexpr T EventFlagsT<T>::ERROR_CANCELED;
432template <typename T> constexpr T EventFlagsT<T>::ERROR_FAIL;
433#endif
434
440
441// ---------------------------------------------------------------------------
442// Set
443// ---------------------------------------------------------------------------
444
445template <typename T>
446inline T EventFlagsT<T>::Set(T flags)
447{
448 T final_result = ERROR_PARAMETER;
449
450 if ((flags != 0U) && ((flags & ERROR_MASK) == 0U))
451 {
453
454 m_flags = static_cast<T>(m_flags | flags);
455 final_result = m_flags;
456
457 // wake all waiters: each task will re-evaluate its own predicate
458 m_cv.NotifyAll_CS();
459 }
460
461 return final_result;
462}
463
464// ---------------------------------------------------------------------------
465// Clear
466// ---------------------------------------------------------------------------
467
468template <typename T>
469inline T EventFlagsT<T>::Clear(T flags)
470{
471 T result = ERROR_PARAMETER;
472
473 if ((flags != 0U) && ((flags & ERROR_MASK) == 0U))
474 {
476
477 result = m_flags;
478 m_flags = static_cast<T>(m_flags & static_cast<T>(~flags));
479 }
480
481 return result;
482}
483
484// ---------------------------------------------------------------------------
485// And
486// ---------------------------------------------------------------------------
487
488template <typename T>
489inline T EventFlagsT<T>::And(T mask)
490{
492
493 const T result = m_flags;
494 m_flags = static_cast<T>(m_flags & mask);
495
496 return result;
497}
498
499// ---------------------------------------------------------------------------
500// Wait
501// ---------------------------------------------------------------------------
502
503template <typename T>
504inline EWaitResult EventFlagsT<T>::WaitCore(T flags, uint32_t options,
505 Timeout timeout_ticks, T &actual_flags)
506{
508
509 const bool timed_wait = (timeout_ticks != WAIT_INFINITE) && (timeout_ticks != NO_WAIT);
510
511 // capture an absolute deadline once, before entering the wait loop,
512 // this prevents the timeout from being silently restarted on each
513 // spurious wakeup (e.g. a partial Set() that does not satisfy OPT_WAIT_ALL)
514 const Timeout deadline = (timed_wait ?
515 static_cast<Timeout>(GetTicks() + timeout_ticks) : timeout_ticks);
516
518
519 // spin (with blocking) until the predicate is satisfied or we time out
520 while (!IsSatisfied(flags, options))
521 {
522 Timeout remaining = deadline;
523 if (timed_wait)
524 {
525 const Timeout now = static_cast<Timeout>(GetTicks());
526 remaining = (now >= deadline ? NO_WAIT : (deadline - now));
527 }
528
529 const EWaitResult wr = m_cv.WaitEx(cs_, remaining);
530
531 if (wr != WAIT_RESULT_SIGNAL)
532 {
533 // timeout (a real deadline miss, or NO_WAIT after 'remaining' collapsed to NO_WAIT),
534 // cancellation by IKernel::CancelTaskWait() or kernel failure: stop immediately,
535 // do not reinterpret the result and do not keep spinning on the predicate
536 result = wr;
537 break;
538 }
539 // else: WAIT_RESULT_SIGNAL - a Set() woke us for re-evaluation (possibly a
540 // spurious/partial match under OPT_WAIT_ALL); loop back and re-check IsSatisfied()
541 }
542
543 // full group snapshot, taken before any auto-clear
544 actual_flags = m_flags;
545
546 if (result == WAIT_RESULT_SIGNAL)
547 {
548 // atomically clear the matched flags unless the caller opted out
549 if ((options & OPT_NO_CLEAR) == 0U)
550 {
551 const T matched = (((options & OPT_WAIT_ALL) == OPT_WAIT_ALL) ?
552 flags : static_cast<T>(m_flags & flags));
553 m_flags = static_cast<T>(m_flags & static_cast<T>(~matched));
554 }
555 }
556
557 return result;
558}
559
560template <typename T>
561inline T EventFlagsT<T>::Wait(T flags, uint32_t options, Timeout timeout_ticks)
562{
563 T final_result = 0U;
564
565 // validate: flags must be non-zero and must not have the error sentinel bit set
566 if ((flags == 0U) || ((flags & ERROR_MASK) != 0U))
567 {
568 final_result = ERROR_PARAMETER;
569 }
570 // ISR check: only NO_WAIT is permitted inside an ISR
571 else if (hw::IsInsideISR() && (timeout_ticks != NO_WAIT))
572 {
573 final_result = ERROR_ISR;
574 }
575 else
576 {
577 T actual = 0U;
578 const EWaitResult wr = WaitCore(flags, options, timeout_ticks, actual);
579
580 if (wr == WAIT_RESULT_SIGNAL)
581 {
582 // predicate satisfied: report the matched flags
583 final_result = (((options & OPT_WAIT_ALL) == OPT_WAIT_ALL) ?
584 flags : static_cast<T>(actual & flags));
585 }
586 else if (wr == WAIT_RESULT_CANCELED)
587 {
588 final_result = ERROR_CANCELED;
589 }
590 else if (wr == WAIT_RESULT_FAIL)
591 {
592 final_result = ERROR_FAIL;
593 }
594 else
595 {
596 final_result = ERROR_TIMEOUT;
597 }
598 }
599
600 return final_result;
601}
602
603template <typename T>
604inline EWaitResult EventFlagsT<T>::WaitEx(T flags, uint32_t options,
605 Timeout timeout_ticks, T &actual_flags)
606{
608
609 if ((flags == 0U) || ((flags & ERROR_MASK) != 0U) ||
610 (hw::IsInsideISR() && (timeout_ticks != NO_WAIT)))
611 {
612 // invalid argument or blocking wait inside an ISR: wait is not performed
613 actual_flags = Get();
614 }
615 else
616 {
617 result = WaitCore(flags, options, timeout_ticks, actual_flags);
618 }
619
620 return result;
621}
622
623// ---------------------------------------------------------------------------
624// Sync
625// ---------------------------------------------------------------------------
626
627template <typename T>
628inline EWaitResult EventFlagsT<T>::Sync(SyncContext &ctx, T set_flags, T wait_flags,
629 Timeout timeout_ticks, T &actual_flags)
630{
632
633 if ((wait_flags == 0U) || ((wait_flags & ERROR_MASK) != 0U) || ((set_flags & ERROR_MASK) != 0U) ||
634 (hw::IsInsideISR() && (timeout_ticks != NO_WAIT)))
635 {
636 // invalid argument or blocking call inside an ISR: nothing is set, nothing is waited for
637 actual_flags = Get();
638 }
639 else
640 {
641 const bool timed_wait = (timeout_ticks != WAIT_INFINITE) && (timeout_ticks != NO_WAIT);
642
643 // absolute deadline captured once (see WaitCore)
644 const Timeout deadline = (timed_wait ?
645 static_cast<Timeout>(GetTicks() + timeout_ticks) : timeout_ticks);
646
648
649 // set this task's bits and remember the rendezvous generation in the same critical section:
650 // the set-then-wait sequence is indivisible for every other task
651 m_flags = static_cast<T>(m_flags | set_flags);
652 const uint32_t gen = ctx.m_gen;
653
654 for (;;)
655 {
656 if (ctx.m_gen != gen)
657 {
658 // released by the task which completed the rendezvous: it has already cleared the flags,
659 // so the predicate must not be re-evaluated here
660 actual_flags = ctx.m_snapshot;
661 result = WAIT_RESULT_SIGNAL;
662 break;
663 }
664
665 if (IsSatisfied(wait_flags, OPT_WAIT_ALL))
666 {
667 // this task completes the rendezvous (last arriver, or flags satisfied by a plain Set()):
668 // publish the snapshot, clear the group flags once and release every blocked participant
669 ctx.m_snapshot = m_flags;
670 m_flags = static_cast<T>(m_flags & static_cast<T>(~wait_flags));
671 ++ctx.m_gen;
672 m_cv.NotifyAll_CS();
673
674 actual_flags = ctx.m_snapshot;
675 result = WAIT_RESULT_SIGNAL;
676 break;
677 }
678
679 Timeout remaining = deadline;
680 if (timed_wait)
681 {
682 const Timeout now = static_cast<Timeout>(GetTicks());
683 remaining = (now >= deadline ? NO_WAIT : (deadline - now));
684 }
685
686 const EWaitResult wr = m_cv.WaitEx(cs_, remaining);
687
688 if (wr != WAIT_RESULT_SIGNAL)
689 {
690 // timeout, cancellation or kernel failure; a completion which raced with the deadline is
691 // still honoured: re-check the generation before giving up
692 if (ctx.m_gen != gen)
693 {
694 actual_flags = ctx.m_snapshot;
695 result = WAIT_RESULT_SIGNAL;
696 }
697 else
698 {
699 actual_flags = m_flags;
700 result = wr;
701 }
702 break;
703 }
704 // else: woken for re-evaluation, loop back
705 }
706 }
707
708 return result;
709}
710
711} // namespace sync
712} // namespace stk
713
714#endif /* STK_SYNC_EVENT_FLAGS_H_ */
#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::ConditionVariable.
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_FAIL
IKernelService::Wait returned with error without waiting.
Definition stk_common.h:139
@ WAIT_RESULT_CANCELED
The wait was cancelled by another task via IKernel::CancelTaskWait(), independent of signal/timeout.
Definition stk_common.h:142
@ 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 Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:448
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
Word TId
Task (thread) id.
Definition stk_common.h:211
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
Synchronization primitives for task coordination and resource protection.
EventFlagsT< uint32_t > EventFlags
Default event flags group with a 32-bit flags word (31 usable flags, bit 31 reserved).
RAII instance that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:495
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:548
Traceable object.
Definition stk_common.h:606
RAII-style low-level synchronization primitive for atomic code execution. Used as building brick for ...
Definition stk_sync_cs.h:58
Condition Variable primitive for signaling between tasks based on specific predicates.
Definition stk_sync_cv.h:68
Event flags group for multi-flag synchronization between tasks, with a selectable flags word type.
T And(T mask)
AND the flags word with a mask (equivalent of ThreadX tx_event_flags_set(TX_AND)).
T Set(T flags)
Set one or more flags.
static constexpr uint32_t OPT_WAIT_ANY
EWaitResult WaitEx(T flags, uint32_t options, Timeout timeout_ticks, T &actual_flags)
Wait for one or more flags to be set, reporting the outcome via EWaitResult.
const IWaitObject::ListHeadType & GetWaitList() const
Get list of tasks blocked on this object.
~EventFlagsT()=default
Destructor.
static constexpr uint32_t OPT_NO_CLEAR
T Clear(T flags)
Clear one or more flags.
static constexpr uint32_t ERROR_CANCELED
T Wait(T flags, uint32_t options=OPT_WAIT_ANY, Timeout timeout_ticks=WAIT_INFINITE)
Wait for one or more flags to be set.
EWaitResult WaitCore(T flags, uint32_t options, Timeout timeout_ticks, T &actual_flags)
T Get() const
Read the current flags word without modifying it.
EventFlagsT(T initial_flags=0U)
Constructor.
T TryWait(T flags, uint32_t options=OPT_WAIT_ANY)
Non-blocking flag poll.
EWaitResult TryWaitEx(T flags, uint32_t options, T &actual_flags)
Non-blocking flag poll with EWaitResult and full flags snapshot.
EWaitResult Sync(SyncContext &ctx, T set_flags, T wait_flags, Timeout timeout_ticks, T &actual_flags)
Atomically set flags and wait for a group of flags: a multi-task rendezvous (equivalent of FreeRTOS x...
static constexpr uint32_t OPT_WAIT_ALL
T ReadFlags(ReadTag< true >) const
Flags word is wider than the native word: a plain load may be split into several, guard it.
static bool IsError(T result)
Checks if a return value from Set(), Clear(), or Wait() is an error.
static constexpr uint32_t ERROR_TIMEOUT
T ReadFlags(ReadTag< false >) const
Flags word fits the native word: a single load is atomic.
static constexpr uint32_t ERROR_PARAMETER
TId GetFirstWaiterTid() const
Get id of the task which is first in the wait list (FIFO order), i.e. the one that WakeOne() would wa...
T FlagsValueType
Flags value type.
bool IsSatisfied(T flags, uint32_t options) const
State of one Sync() rendezvous group, supplied by the caller.
T m_snapshot
flags word captured when the last rendezvous completed
uint32_t m_gen
rendezvous generation, incremented when the rendezvous completes
Selects how the flags word is read: WIDE is true if T is wider than a pointer.