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
/*
* SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
*
* Source: https://github.com/SuperTinyKernel-RTOS
*
* Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
* License: MIT License, see LICENSE for a full text.
*/
#include <stk.h>
#include "example.h"
// Warning: On ARM Cortex-M you can use fast TLS via R9 CPU register: for that define
// STK_TLS_PREFER_REGISTER to (1) and use -ffixed-r9 compiler flag which prevents
// compiler from allocating r9 as a scratch or callee-saved register.
// Sync primitive used:
//
// Semaphore (one per task) - each task blocks on its own semaphore; the
// running task signals the next task's semaphore after its 1-second sleep.
// With per-task semaphores the handover is point-to-point - exactly one
// task is woken per Signal(), with no counter to check and no Reset() needed.
// Kernel instance must be created with KERNEL_SYNC flag to support synchronization
// objects.
using namespace bsp;
// One semaphore per LED task. Initial count 0: all tasks block on Wait()
// until their semaphore is signaled. task0 is pre-seeded with count 1 so
// it runs first without any external trigger.
static stk::sync::Semaphore g_Sem0(1); // task 0 runs first
// Indexed accessor so task template code can use g_Sem[_TaskId] style.
{
};
// Timeline for a precise LED switching
// Simple thread-local storage, the complexity can be any
struct MyTls
{
};
// Task function switching the LED, TLS provides the ID of the task for the logic of this function
static void SwitchOnLED()
{
// for demonstration purpose we get task_id from our TLS and switch on corresponding LED
Led::Id led = stk::hw::GetTlsPtr<MyTls>()->led;
}
// R2350 requires larger stack due to stack-memory heavy SDK API
#ifdef _PICO_H
enum { TASK_STACK_SIZE = 1024 };
#else
enum { TASK_STACK_SIZE = 256 };
#endif
// Task's core (thread)
// _TaskId maps directly to a semaphore slot and the next-task index.
template <uint8_t _TaskId, Led::Id _LedId, stk::EAccessMode _AccessMode>
class MyTask : public stk::Task<TASK_STACK_SIZE, _AccessMode>
{
MyTls m_tls; // task-local TLS, you can provide your own implementation
public:
{
// init TLS with id of the LED (see SwitchOnLED)
m_tls.led = _LedId;
}
private:
void Run() override
{
// set TLS for this task
stk::hw::SetTlsPtr(&m_tls);
while (true)
{
// block until the previous task signals our semaphore,
// each task owns exactly one semaphore slot - no broadcast wake,
// no shared counter to check, no Reset() required
g_Sem[_TaskId]->Wait();
// it is static function and does not have the 'this' pointer to the task instance
// we use TLS to get the led id
// sleep 1s and delegate work to another task switching another LED
// we could sleep with a simple stk::Sleep if precision is not needed, but in other
// case we could sleep until calculated precise timestamp to avoid a time drift
//stk::SleepMs(1000);
// hand off to the next task in the ring by signaling its semaphore
// Signal() is ISR-safe: could also be called from a hardware timer ISR
// to drive the ring externally without changing any task code
g_Sem[(_TaskId + 1) % 4]->Signal();
}
}
};
void RunExample()
{
using namespace stk;
Led::InitAll(false);
// allocate scheduling kernel for 4 threads (tasks) with Round-robin scheduling strategy
static Kernel<KERNEL_STATIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0), 4,
// note: using ACCESS_PRIVILEGED as Cortex-M7 or Cortex-M33 may require privileged access to peripherals
// init scheduling kernel
kernel.Initialize();
// register threads (tasks)
kernel.AddTask(&task1);
kernel.AddTask(&task2);
kernel.AddTask(&task3);
kernel.AddTask(&task4);
// start scheduler (it will start threads added by AddTask), execution in main() will be blocked on this line
kernel.Start();
// shall not reach here after Start() was called
STK_ASSERT(false);
}
@ 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
bool Wait(Timeout timeout_ticks=WAIT_INFINITE)
Wait for a signal (decrement counter).
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)
static stk::sync::Semaphore g_Sem0(1)