Skip to content
systemcoding.dev
RTOS

Create Zephyr Threads With K_THREAD_DEFINE

Use K_THREAD_DEFINE to create a Zephyr thread at build time, with stack size, priority and start delay, plus the thread entry signature and how to stop it.

6 min read
Summarize in AI
Flat illustration of RTOS tasks taking turns on a timeline, with the C, Espressif and Arm logos.

A single loop in main() is enough for a blinking LED and not much more. As soon as a program has to read a sensor, answer a command and update a display, each job wants its own flow of control that can wait without holding up the others. In Zephyr that flow of control is a thread, and the simplest way to create one is the K_THREAD_DEFINE macro. It reserves the stack and the bookkeeping at build time and starts the thread when the kernel boots. This post shows the macro, explains each argument, and builds a two-thread program in Zephyr 4.2, as a first step into the material of the threads and synchronization guide.

What the macro does

K_THREAD_DEFINE is declared in <zephyr/kernel.h>. It takes nine arguments:

c
K_THREAD_DEFINE(name, stack_size, entry, p1, p2, p3, prio, options, delay);

The first is the name, and each argument has a job:

ArgumentMeaning
nameAn identifier. The macro defines a variable of this name holding the thread id
stack_sizeStack size in bytes
entryThe function the thread runs
p1, p2, p3Three values passed to the entry function
prioThe thread priority. Lower numbers are more urgent
optionsFlags such as K_ESSENTIAL, or 0 for none
delayMilliseconds to wait before starting, or 0 to start immediately

The macro creates a static stack and a thread control block, and registers the thread so that the kernel starts it during boot. You do not call a function to launch it. The name becomes a variable of type k_tid_t that you can pass to calls such as k_thread_suspend(name).

The entry function

Every thread entry function has the same signature, three void * parameters and no return value:

c
static void sensor_thread(void *p1, void *p2, void *p3)
{
	ARG_UNUSED(p1);
	ARG_UNUSED(p2);
	ARG_UNUSED(p3);

	while (1) {
		/* work */
		k_msleep(100);
	}
}

The parameters carry whatever you pass as p1, p2 and p3 in the macro. If you do not need them, pass NULL and mark them unused. When the function returns, the thread ends. Most embedded threads loop forever, since there is nothing to return to.

A pointer parameter can carry an integer by casting. This is common and legal for small values:

c
static void worker(void *p1, void *p2, void *p3)
{
	int id = (int)(intptr_t)p1;

	printk("worker %d started\n", id);
}

K_THREAD_DEFINE(worker_a, 1024, worker, (void *)1, NULL, NULL, 5, 0, 0);
K_THREAD_DEFINE(worker_b, 1024, worker, (void *)2, NULL, NULL, 5, 0, 0);

Two threads share one entry function and each receives its own number. That gives them distinct stacks and distinct control blocks, because each macro use defines its own.

A complete program

This program starts two threads with different periods and lets main() report a status line:

src/main.cc
#include <zephyr/kernel.h>

#define STACK_SIZE 1024
#define PRIO_FAST  4
#define PRIO_SLOW  6

static void fast_thread(void *p1, void *p2, void *p3)
{
	ARG_UNUSED(p1);
	ARG_UNUSED(p2);
	ARG_UNUSED(p3);

	int n = 0;

	while (1) {
		printk("fast %d\n", n++);
		k_msleep(250);
	}
}

static void slow_thread(void *p1, void *p2, void *p3)
{
	ARG_UNUSED(p1);
	ARG_UNUSED(p2);
	ARG_UNUSED(p3);

	int n = 0;

	while (1) {
		printk("slow %d\n", n++);
		k_msleep(1000);
	}
}

K_THREAD_DEFINE(fast_id, STACK_SIZE, fast_thread, NULL, NULL, NULL, PRIO_FAST, 0, 0);
K_THREAD_DEFINE(slow_id, STACK_SIZE, slow_thread, NULL, NULL, NULL, PRIO_SLOW, 0, 500);

int main(void)
{
	printk("main started\n");
	return 0;
}
prj.confText
CONFIG_PRINTK=y

The slow thread has a start delay of 500 ms, so its first line appears after the fast thread's third. A run looks like this:

Text
*** Booting Zephyr OS build v4.2.0 ***
main started
fast 0
fast 1
slow 0
fast 2
fast 3
fast 4
fast 5
slow 1
fast 6

main() returns after printing its line, and the other threads keep running. Returning from main() only ends the main thread. The exact interleaving depends on timing, and the relative order of lines at the same tick is not guaranteed.

Choosing the stack size

The stack holds the thread's local variables, function-call frames and interrupt frames. A size of 1024 bytes is a common starting point for a thread that calls printk and a few functions, and 2048 or more is typical when a thread uses printf-style formatting, logging or a network stack. If the size is too small, the thread overflows into neighboring memory, with effects that range from nothing to a crash far away from the cause.

Measure rather than guess. With CONFIG_THREAD_ANALYZER=y and CONFIG_THREAD_ANALYZER_AUTO=y, the kernel prints each thread's stack high-water mark at an interval. The guide to threads shows the output. Zephyr also provides CONFIG_HW_STACK_PROTECTION on chips that have a memory protection unit, which turns an overflow into a clear fault, covered in a later post. Stack sizes in K_THREAD_DEFINE count against RAM at build time, so ten threads of 2048 bytes use 20 KiB, and the link fails if there is not enough.

Choosing the priority

The prio argument decides who runs when several threads are ready. In Zephyr a smaller number runs first, a negative number is cooperative, and a non-negative number is preemptible. For ordinary application threads use values between about 5 and 15, so that you can add more urgent threads later with smaller numbers. The main thread's default priority comes from CONFIG_MAIN_THREAD_PRIORITY, normally 0, so a thread with priority 5 is less urgent than main() by default. The post on cooperative versus preemptive priorities explains the ranges.

Starting later and controlling the thread

The delay argument lets you stagger startup, which is useful when one thread depends on another's initialization. A delay of K_FOREVER creates the thread but does not start it until you call k_thread_start(id):

c
K_THREAD_DEFINE(late_id, 1024, late_thread, NULL, NULL, NULL, 7, 0, K_FOREVER);

void on_ready(void)
{
	k_thread_start(late_id);
}

The thread id variable is also what you pass to control calls: k_thread_suspend(id), k_thread_resume(id), k_thread_priority_set(id, prio) and k_thread_abort(id). Naming the thread for debuggers takes CONFIG_THREAD_NAME=y and a call to k_thread_name_set(id, "sensor") at startup. Prefer a flag the thread checks over k_thread_abort, since aborting a thread that holds a lock leaves the lock held forever.

K_THREAD_DEFINE versus k_thread_create

The two ways of creating a thread suit different needs:

K_THREAD_DEFINEk_thread_create
When it is createdBuild time, started by the kernelRun time, when your code calls it
StackReserved by the macroYou define it with K_THREAD_STACK_DEFINE
Number of threadsFixedCan depend on run-time conditions
Code neededOne lineSeveral lines
Use forFixed set of long-lived threadsThreads that start on demand

Most embedded firmware has a fixed set of long-lived threads, so K_THREAD_DEFINE is the right default. Use k_thread_create when a thread is started in response to an event, and know that its stack and control block must stay valid for the thread's lifetime, so they are typically static.

Common mistakes

A thread function that returns by accident. If the entry function has a path that returns, the thread silently ends. For a service thread, end the body with an endless loop.

A busy loop with no waiting. A thread that never blocks keeps the CPU from every thread of lower priority. Always include a k_msleep, a wait on a semaphore or a queue.

Two macros with the same name. The name defines a variable, so duplicates collide at link time. Use distinct names.

Printing from many threads. printk is not synchronized between threads on every console backend, so output from concurrent threads can interleave in the middle of a line. Use the logging subsystem, which formats each message as a unit, when output readability matters.

**A stack that is too small for printk with floating point.** Formatting %f needs a larger stack and extra configuration. Check CONFIG_CBPRINTF_FP_SUPPORT.

The thread reference is in the Zephyr threads documentation.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.