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
sync/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.
*/
/*
* A control task toggles a state every second and sends it to a hardware LED task through a
* stk::sync::PipeT (or, with STK_EXAMPLE_USE_PIPE set to 0, through stk::sync::Event objects). The LED
* task blocks on the pipe with a timeout, protects the hardware access with a stk::sync::Mutex and signals
* that it is ready with an Event. Variants for a single core, a user-mode control task and a dual-core MCU
* (RP2350) are provided.
*/
//#define _STK_ASSERT_REDIRECT
#ifdef _STK_ASSERT_REDIRECT
#include <stdint.h>
extern void STK_ASSERT_HANDLER(const char *err, const char *source, int32_t line);
#endif
#include <stk.h>
#include <sync/stk_sync.h>
#include "example.h"
using namespace bsp;
#ifdef _PICO_H
#define STK_EXAMPLE_DUALCORE 1
#else
#define STK_EXAMPLE_DUALCORE 0
#endif
#define STK_EXAMPLE_USE_PIPE 1
// 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
#ifdef _STK_ASSERT_REDIRECT
void STK_ASSERT_HANDLER(const char *err, const char *source, int32_t line)
{
while (true) {}
}
#endif
{
LED_OFF = 0,
};
#if STK_EXAMPLE_USE_PIPE
#else
static stk::sync::Event g_EventReady, g_EventSwitchOn, g_EventSwitchOff;
#endif
// Task's core (thread)
template <stk::EAccessMode _AccessMode>
class LedTask : public stk::Task<2048, _AccessMode>
{
public:
LedTask(LedState task_id) : m_task_id(task_id)
{}
private:
void Run()
{
LedState task_id = m_task_id;
while (true)
{
// time out in 100ms (just as an example, can be WAIT_INFINITE for max power saving)
#if STK_EXAMPLE_USE_PIPE
if (!g_CtrlSignalPipe.Read(task_id, 100))
continue;
#else
switch (task_id)
{
case LED_ON:
if (!g_EventSwitchOn.Wait(100))
continue;
break;
case LED_OFF:
if (!g_EventSwitchOff.Wait(100))
continue;
break;
}
#endif
// switch LED on/off
{
// we do not want preemption during IO with hardware
stk::sync::Mutex::ScopedLock guard(g_HwMutex);
Led::Set(Led::GREEN, (task_id == LED_OFF ? false : true));
}
#if !STK_EXAMPLE_USE_PIPE
g_EventReady.Set();
#endif
}
}
};
// Task's core (thread)
template <stk::EAccessMode _AccessMode>
class CtrlTask : public stk::Task<TASK_STACK_SIZE, _AccessMode>
{
private:
void Run()
{
int64_t task_start = stk::GetTimeNowMs();
#if !STK_EXAMPLE_USE_PIPE
g_EventReady.Set();
#endif
bool led_sw = false;
while (true)
{
#if !STK_EXAMPLE_USE_PIPE
if (!g_EventReady.Wait())
continue;
#endif
// sleep 1s and delegate work to another task switching another LED, hw thread could have
// some latency, thus account for it
int32_t sleep = 250 + (int32_t)(task_start - stk::GetTimeNowMs());
if (sleep > 0)
led_sw = !led_sw;
task_start = stk::GetTimeNowMs();
#if STK_EXAMPLE_USE_PIPE
continue;
#else
if (led_sw)
g_EventSwitchOn.Set();
else
g_EventSwitchOff.Set();
#endif
}
}
};
#if STK_EXAMPLE_DUALCORE
void StartCore0()
{
using namespace stk;
// allocate scheduling kernel for 1 thread (tasks) with Round-robin scheduling strategy
// these are secure/trusted tasks which are allowed to access hardware safely
static LedTask<ACCESS_PRIVILEGED> secure_hw_task0(LED_OFF);
#if !STK_EXAMPLE_USE_PIPE
static LedTask<ACCESS_PRIVILEGED> secure_hw_task1(LED_ON);
#endif
// init scheduling kernel
kernel.Initialize();
// register threads (tasks)
kernel.AddTask(&secure_hw_task0);
#if !STK_EXAMPLE_USE_PIPE
kernel.AddTask(&secure_hw_task1);
#endif
// 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);
}
void StartCore1()
{
using namespace stk;
// allocate scheduling kernel for 1 thread (tasks) with Round-Robin scheduling strategy
// if MCU supports (for example Cortex-M7/M33), ACCESS_USER does not allow an access to a hardware directly,
// therefore you can process in this thread/task an insecure context or data
static CtrlTask<ACCESS_USER> unsecure_task;
// init scheduling kernel
kernel.Initialize();
// register threads (tasks)
kernel.AddTask(&unsecure_task);
// 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);
}
void RunExample()
{
// optional, for debugging only
#if !STK_EXAMPLE_USE_PIPE
g_EventReady.SetTraceName("rdy");
g_EventSwitchOn.SetTraceName("sw-on");
g_EventSwitchOff.SetTraceName("sw-off");
#endif
// start on the main core (0) in the last step as it will be the last blocking call of RunExample
// shall not reach here after Start() was called
STK_ASSERT(false);
}
#else
void RunExample()
{
using namespace stk;
Led::InitAll(false);
// allocate scheduling kernel for 1 thread (tasks) with Round-Robin scheduling strategy
static Kernel<KERNEL_STATIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0), 3,
// these are secure/trusted tasks which are allowed to access hardware safely
static LedTask<ACCESS_PRIVILEGED> secure_hw_task0(LED_OFF);
#if !STK_EXAMPLE_USE_PIPE
static LedTask<ACCESS_PRIVILEGED> secure_hw_task1(LED_ON);
#endif
// if MCU supports (for example Cortex-M7/M33), ACCESS_USER does not allow an access to a hardware directly,
// therefore you can process in this thread/task an insecure context or data
static CtrlTask<ACCESS_USER> unsecure_task;
// optional, for debugging only
#if !STK_EXAMPLE_USE_PIPE
g_EventReady.SetTraceName("rdy");
g_EventSwitchOn.SetTraceName("sw-on");
g_EventSwitchOff.SetTraceName("sw-off");
#endif
// init scheduling kernel
kernel.Initialize();
// register threads (tasks)
kernel.AddTask(&secure_hw_task0);
#if !STK_EXAMPLE_USE_PIPE
kernel.AddTask(&secure_hw_task1);
#endif
kernel.AddTask(&unsecure_task);
// 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);
}
#endif
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
static void __stk_debug_break()
Definition stk_defs.h:495
Collection of synchronization primitives (stk::sync namespace).
unsigned int sleep(unsigned int seconds)
Suspend for seconds seconds. Cancellation point.
Namespace of STK package.
static Time GetTimeNowMs()
Get current time in milliseconds since kernel start.
Definition stk_helper.h:459
static bool Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:495
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.
Definition cpu.h:17
Concrete implementation of IKernel.
Definition stk.h:102
void Start() override
Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or i...
Definition stk.h:1999
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
void SetTraceName(const char *name)
Set name.
Definition stk_common.h:617
Partial implementation of the user task.
Definition stk_helper.h:98
Binary synchronization event (signaled / non-signaled) primitive.
bool Set()
Set event to signaled state.
bool Wait(Timeout timeout_ticks=WAIT_INFINITE)
Wait until event becomes signaled or the timeout expires.
Recursive mutex primitive that allows the same thread to acquire the lock multiple times.
Thread-safe, type-safe FIFO communication pipe with internal storage.
bool Write(const T &data, Timeout timeout_ticks=WAIT_INFINITE)
Write data to the pipe.
bool Read(T &data, Timeout timeout_ticks=WAIT_INFINITE)
Read data from the pipe.
void Run()
Entry point of the user task.
void Run() override
Entry point of the user task.
static void Start(uint8_t cpu_id, void(*entry_func)(void))
Definition cpu.cpp:24
static void InitAll(bool init_state)
Definition led.h:40
void StartCore1()
void StartCore0()
LedTaskT< stk::ACCESS_PRIVILEGED > LedTask
#define TASK_STACK_SIZE
LedState
@ LED_ON
@ LED_OFF
static stk::sync::PipeT< LedState, 1 > g_CtrlSignalPipe
static stk::sync::Mutex g_HwMutex
static void InitLeds()