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
tls/example.cpp
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
15
16#include <stk.h>
17#include "example.h"
18
19// Warning: On ARM Cortex-M you can use fast TLS via R9 CPU register: for that define
20// STK_TLS_PREFER_REGISTER to (1) and use -ffixed-r9 compiler flag which prevents
21// compiler from allocating r9 as a scratch or callee-saved register.
22
23// Sync primitive used:
24//
25// Semaphore (one per task) - each task blocks on its own semaphore; the
26// running task signals the next task's semaphore after its 1-second sleep.
27// With per-task semaphores the handover is point-to-point - exactly one
28// task is woken per Signal(), with no counter to check and no Reset() needed.
29// Kernel instance must be created with KERNEL_SYNC flag to support synchronization
30// objects.
32
33using namespace bsp;
34
35// One semaphore per LED task. Initial count 0: all tasks block on Wait()
36// until their semaphore is signaled. task0 is pre-seeded with count 1 so
37// it runs first without any external trigger.
38static stk::sync::Semaphore g_Sem0(1); // task 0 runs first
42
43// Indexed accessor so task template code can use g_Sem[_TaskId] style.
45{
47};
48
49// Timeline for a precise LED switching
51
52// Simple thread-local storage, the complexity can be any
53struct MyTls
54{
56};
57
58// Task function switching the LED, TLS provides the ID of the task for the logic of this function
59static void SwitchOnLED()
60{
61 // for demonstration purpose we get task_id from our TLS and switch on corresponding LED
62 Led::Id led = stk::hw::GetTlsPtr<MyTls>()->led;
63
65}
66
67// R2350 requires larger stack due to stack-memory heavy SDK API
68#ifdef _PICO_H
69enum { TASK_STACK_SIZE = 1024 };
70#else
71enum { TASK_STACK_SIZE = 256 };
72#endif
73
74// Task's core (thread)
75// _TaskId maps directly to a semaphore slot and the next-task index.
76template <uint8_t _TaskId, Led::Id _LedId, stk::EAccessMode _AccessMode>
77class MyTask : public stk::Task<TASK_STACK_SIZE, _AccessMode>
78{
79 MyTls m_tls; // task-local TLS, you can provide your own implementation
80
81public:
83 {
84 // init TLS with id of the LED (see SwitchOnLED)
85 m_tls.led = _LedId;
86 }
87
88private:
89 void Run() override
90 {
91 // set TLS for this task
92 stk::hw::SetTlsPtr(&m_tls);
93
95
96 while (true)
97 {
98 // block until the previous task signals our semaphore,
99 // each task owns exactly one semaphore slot - no broadcast wake,
100 // no shared counter to check, no Reset() required
101 g_Sem[_TaskId]->Wait();
102
103 // it is static function and does not have the 'this' pointer to the task instance
104 // we use TLS to get the led id
105 SwitchOnLED();
106
107 // sleep 1s and delegate work to another task switching another LED
108 // we could sleep with a simple stk::Sleep if precision is not needed, but in other
109 // case we could sleep until calculated precise timestamp to avoid a time drift
110 //stk::SleepMs(1000);
113
114 // hand off to the next task in the ring by signaling its semaphore
115 // Signal() is ISR-safe: could also be called from a hardware timer ISR
116 // to drive the ring externally without changing any task code
117 g_Sem[(_TaskId + 1) % 4]->Signal();
118 }
119 }
120};
121
123{
124 using namespace stk;
125
126 Led::InitAll(false);
127
128 // allocate scheduling kernel for 4 threads (tasks) with Round-robin scheduling strategy
129 static Kernel<KERNEL_STATIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0), 4,
131
132 // note: using ACCESS_PRIVILEGED as Cortex-M7 or Cortex-M33 may require privileged access to peripherals
137
138 // init scheduling kernel
139 kernel.Initialize();
140
141 // register threads (tasks)
142 kernel.AddTask(&task1);
143 kernel.AddTask(&task2);
144 kernel.AddTask(&task3);
145 kernel.AddTask(&task4);
146
147 // start scheduler (it will start threads added by AddTask), execution in main() will be blocked on this line
148 kernel.Start();
149
150 // shall not reach here after Start() was called
151 STK_ASSERT(false);
152}
@ LED_MAX
Definition led.h:22
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
Implementation of synchronization primitive: stk::sync::SemaphoreT and stk::sync::Semaphore.
Namespace of STK package.
int64_t Ticks
Ticks value.
Definition stk_common.h:221
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:523
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:406
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:448
PlatformArmCortexM PlatformDefault
Default platform implementation.
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
@ KERNEL_STATIC
All tasks are static and can not exit.
Definition stk_common.h:47
SwitchStrategyRoundRobinT< false > SwitchStrategyRR
Shorthand alias for SwitchStrategyRoundRobin.
SemaphoreT< uint16_t > Semaphore
Default counting semaphore with a 16-bit counter (max count 0xFFFF).
Definition cpu.h:17
Concrete implementation of IKernel.
Definition stk.h:102
Partial implementation of the user task.
Definition stk_helper.h:98
MyTls m_tls
void Run() override
Entry point of the user task.
LedId Id
Definition led.h:32
static void InitAll(bool init_state)
Definition led.h:40
static void SwitchOnExclusive(Id led)
Definition led.h:48
Led::Id led
static stk::Ticks g_Timeline
#define TASK_STACK_SIZE
static stk::Ticks g_Timeline
static stk::sync::Semaphore g_Sem1(0)
static void SwitchOnLED()
static stk::sync::Semaphore *const g_Sem[LED_MAX]
static stk::sync::Semaphore g_Sem3(0)
static stk::sync::Semaphore g_Sem2(0)
void RunExample()
static stk::sync::Semaphore g_Sem0(1)