Start a thread at runtime with k_thread_create
k_thread_create starts a thread from static stack and k_thread storage; a lower priority number means a higher priority, in Zephyr 4.2.
K_THREAD_DEFINE creates a thread at boot. When you need one at run time, k_thread_create() takes the pieces separately: the struct k_thread, a stack, the entry function, three pointer arguments, a priority, options and a start delay. Both the control block and the stack must outlive the thread, so make them static.
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include <stdint.h>
#define STACK_SIZE 1024
K_THREAD_STACK_DEFINE(worker_stack, STACK_SIZE);
static struct k_thread worker_data;
static void worker(void *p1, void *p2, void *p3)
{
printk("worker got %d\n", (int)(intptr_t)p1);
}
int main(void)
{
k_tid_t tid = k_thread_create(&worker_data, worker_stack,
K_THREAD_STACK_SIZEOF(worker_stack),
worker, (void *)(intptr_t)42, NULL, NULL,
5, 0, K_NO_WAIT);
k_thread_join(tid, K_FOREVER);
printk("joined\n");
return 0;
}worker got 42
joinedThe main thread runs at priority 0, so priority 5 is lower: the worker does not run until main blocks in k_thread_join(). Smaller numbers win, and negative numbers are cooperative. When the entry function returns, the thread ends and its stack can be reused once k_thread_join() returns. Never put either object on a stack that disappears first. The call is described in the threads documentation. Zephyr 4.2 is the version used.