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
blinky_c-pthread/example.c
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/*
17 * Blinky built on the STK pthread API (stk_c_pthread.h).
18 *
19 * Four LED threads pass a "baton" to each other: only the thread whose turn it is
20 * lights its LED (exclusively), keeps it on for 1 s, then hands the turn to the next
21 * thread. Mutex + condition variable replace the EventFlags used in example.c.
22 *
23 * Kernel requirements (stk_config.h):
24 * - STK_C_KERNEL_TYPE_CPU_0 must be a KERNEL_DYNAMIC kernel, with KERNEL_SYNC for
25 * the mutex/condvar, e.g.:
26 * #define STK_C_KERNEL_TYPE_CPU_0 Kernel<KERNEL_DYNAMIC | KERNEL_SYNC, STK_C_KERNEL_MAX_TASKS, SwitchStrategyRR, PlatformDefault>
27 * - STK_C_KERNEL_MAX_TASKS >= 1 (main task) + LED_MAX (threads) + 1 (internal reaper,
28 * created lazily) = 6 for 4 LEDs.
29 */
30
31#include <pthread.h>
32#include <stk_c.h>
33#include "example.h"
34
35enum { MAIN_STACK_SIZE = 256, THREAD_STACK_SIZE = 256 }; // in stk_word_t units
36
37// Bootstrap (main) task stack and one stack per LED thread
40
41// Baton: the id of the LED thread whose turn it is (RED goes first)
44static uint32_t g_Baton = LED_RED;
45
46// Timeline for precise (drift-free) LED switching
48
50
51// Evaluate a pthread call and assert it returned 0 (stays side-effect safe with NDEBUG)
52#define PT_CHECK(call) do { int rc_ = (call); STK_C_ASSERT(rc_ == 0); (void)rc_; } while (0)
53
54static void *LedThread(void *arg)
55{
56 const uint32_t id = (uint32_t)(uintptr_t)arg;
57 const uint32_t next = (id + 1U) % LED_MAX;
58 const stk_tick_t period = stk_ticks_from_ms(250);
59
60 while (true)
61 {
62 // block until it is this thread's turn
64 while (g_Baton != id)
65 {
67 }
69
70 // change LED state
71 {
75 }
76
77 // sleep 1s drift-free: only the baton holder touches g_Timeline, so no locking needed
78 g_Timeline += period;
80
81 // hand off to the next thread
83 g_Baton = next;
86 }
87
88 return NULL; // never reached
89}
90
91// Bootstrap task: creates the LED threads, then waits for them (they never finish)
92static void MainTask(void *arg)
93{
94 (void)arg;
95
96 // initialize explicitly (instead of lazily on first use) to avoid any first-use race
99
100 // start of the timeline
102
103 for (uint32_t i = 0; i < LED_MAX; i++)
104 {
105 pthread_attr_t attr;
107
108 // caller-owned static stack: avoids the default 1024-word pool and malloc()
110 sizeof(g_ThreadStack[i])));
111
112 // privileged thread: some MCUs (e.g. Cortex-M7/M33) do not allow GPIO access from user mode
114
115 PT_CHECK(pthread_create(&g_Threads[i], &attr, LedThread, (void *)(uintptr_t)i));
117 }
118
119 // block forever
120 for (uint32_t i = 0; i < LED_MAX; i++)
121 {
122 pthread_join(g_Threads[i], NULL);
123 }
124}
125
127{
128 Led_InitAll(false);
129
130 // allocate scheduling kernel (KERNEL_DYNAMIC + KERNEL_SYNC required for pthreads)
132 STK_C_ASSERT(k != NULL);
133
134 // init kernel with default periodicity - 1ms tick
136
137 // tell the pthread shim which kernel pthread_create() adds threads to
139
140 stk_task_t *main_task = stk_task_create_user(MainTask, NULL,
141 STK_GET_STACK_FROM_POOL(g_MainStack, 0),
143 STK_C_ASSERT(main_task != NULL);
144
145 stk_kernel_add_task(k, main_task);
146
147 // start scheduler, execution in main() will be blocked on this line
149
150 // shall not reach here after stk_kernel_start() was called
151 STK_C_ASSERT(false);
152}
void Led_InitAll(bool state)
Definition c_wrapper.cpp:27
void Led_SwitchOnExclusive(LedId led)
Definition c_wrapper.cpp:32
LedId
Definition led.h:16
@ LED_MAX
Definition led.h:22
@ LED_RED
Definition led.h:19
C language binding/interface for SuperTinyKernel RTOS.
POSIX-named entry point for the STK pthread shim (stk_c_pthread.h).
stk_task_t * stk_task_create_user(stk_task_entry_t entry, void *arg, stk_word_t *stack, uint32_t stack_size)
Create user-mode task.
Definition stk_c.cpp:662
#define STK_GET_STACK_FROM_POOL(name, task_id)
Retrieves the base stack pointer for a specific task ID from a stack pool.
Definition stk_c.h:292
stk_tick_t stk_ticks_from_ms(stk_time_t msec)
Get ticks from milliseconds using current kernel tick resolution.
Definition stk_c.cpp:792
struct stk_kernel_t stk_kernel_t
Opaque handle to a kernel instance.
Definition stk_c.h:188
void stk_kernel_start(stk_kernel_t *k)
Start the scheduler - never returns.
Definition stk_c.cpp:478
stk_add_result_t stk_kernel_add_task(stk_kernel_t *k, stk_task_t *tsk)
Add task to non-HRT kernel (static or dynamic).
Definition stk_c.cpp:506
#define STK_DEFINE_STACK_POOL(name, max_tasks, stack_size)
Allocates a statically bound, multi-dimensional stack pool for tasks.
Definition stk_c.h:283
#define STK_PERIODICITY_DEFAULT
Default tick period (1 ms).
Definition stk_c.h:196
void stk_kernel_init(stk_kernel_t *k, uint32_t tick_period_us)
Initialize kernel with given tick period.
Definition stk_c.cpp:471
stk_tick_t stk_ticks(void)
Returns number of ticks elapsed since kernel start.
Definition stk_c.cpp:789
void stk_critical_section_enter()
Enter global critical section - disable context switches on current core.
Definition stk_c.cpp:834
int64_t stk_tick_t
Ticks value.
Definition stk_c.h:165
stk_kernel_t * stk_kernel_create(uint8_t core_nr)
Create kernel.
Definition stk_c.cpp:403
#define STK_C_ASSERT(e)
Assertion macro used inside STK C bindings.
Definition stk_c.h:104
bool stk_sleep_until(stk_tick_t ts)
Put current task to sleep (non-HRT kernels only).
Definition stk_c.cpp:800
void stk_critical_section_exit()
Leave global critical section - re-enable context switches.
Definition stk_c.cpp:841
int pthread_attr_init(pthread_attr_t *attr)
Initialize a thread attributes object with default values (default stack size, no external stack,...
int pthread_mutex_lock(pthread_mutex_t *mutex)
Lock a mutex, blocking until it becomes available.
int pthread_join(pthread_t thread, void **retval)
Block until the given joinable thread finishes, then reclaim its resources.
#define PTHREAD_CREATE_PRIVILEGED_NP
int pthread_attr_destroy(pthread_attr_t *attr)
Destroy a thread attributes object (no-op; no owned resources).
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Initialize a mutex.
int pthread_attr_setprivileged_np(pthread_attr_t *attr, int mode)
Non-portable: select the STK access mode of threads created with attr.
struct pthread_stk_ctrl_t * pthread_t
Opaque thread handle.
#define PTHREAD_MUTEX_INITIALIZER
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Atomically unlock mutex and wait for a signal; re-locks mutex before returning.
int pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize)
Supply an external, caller-owned stack buffer for the thread.
int pthread_mutex_unlock(pthread_mutex_t *mutex)
Unlock a mutex held by the calling thread.
#define PTHREAD_COND_INITIALIZER
void stk_pthread_bind_kernel(void *kernel)
Bind the STK kernel instance that pthread_create() will add new threads to.
int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Initialize a condition variable.
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Create and start a new thread.
int pthread_cond_broadcast(pthread_cond_t *cond)
Wake all threads waiting on cond (no effect if none is waiting).
Thread creation attributes.
A pthread mutex.
A pthread condition variable.
static stk::Ticks g_Timeline
static void MainTask(void *arg)
static void * LedThread(void *arg)
static pthread_mutex_t g_Lock
#define PT_CHECK(call)
static pthread_t g_Threads[LED_MAX]
static uint32_t g_Baton
static pthread_cond_t g_Turn