The Complete Guide to Zephyr Kernel Threads and Synchronisation
Learn Zephyr threads, priorities, timers, work queues, semaphores, mutexes and message queues, with working examples and a rule for picking each primitive.

A Zephyr application is a set of cooperating threads, and almost every bug in a non-trivial one is about how those threads share time and data. A sensor thread that blocks the main loop, a counter that two contexts update at once, a queue that fills while a consumer sleeps, a low-priority thread holding a lock a high-priority thread needs: each is a synchronization problem, and each has a primitive built to solve it. This guide takes you from creating your first thread to choosing among semaphores, mutexes, message queues, work queues and events, using Zephyr 4.2 on any board. It assumes you can build and run a program as shown in the post on application structure, and it ends with the limits of the kernel's model and where to read next.
The mental model
Zephyr is a single-address-space kernel with a priority-based scheduler. Your program is a collection of threads that share one memory space. At any moment on a single-core system exactly one thread runs, and the scheduler decides which one when something changes: a thread blocks, a timer fires, an interrupt makes a higher-priority thread ready.
Three ideas carry most of what follows.
A thread is a function with its own stack. Each thread has an entry function, a stack of fixed size, a priority and a state. The stack is reserved at build time or at creation, and it does not grow, so the size you choose is a commitment.
The scheduler picks the highest-priority ready thread. Priorities are integers. In Zephyr, a lower number means higher priority, which surprises people who expect the opposite. If two ready threads have the same priority, one runs until it blocks, yields, or exhausts a time slice, if time slicing is on.
Synchronization primitives are the only safe way to share. Threads do not run in parallel on one core, but they can be preempted between any two instructions. A read-modify-write of a shared variable is not atomic unless you make it so. Primitives such as semaphores, mutexes and queues make the handoff safe and, just as important, let a thread wait without spinning.
The official references are the threads documentation and the pages for each kernel service. This guide follows the same split, adds the worked examples, and puts a decision rule at the end.
Your first thread
The shortest way to create a thread is the K_THREAD_DEFINE macro, which allocates the stack and the thread control block at build time and starts the thread when the kernel boots:
#include <zephyr/kernel.h>
#define STACK_SIZE 1024
#define PRIORITY 5
static void blinker(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
int n = 0;
while (1) {
printk("blinker %d\n", n++);
k_msleep(500);
}
}
K_THREAD_DEFINE(blinker_id, STACK_SIZE, blinker, NULL, NULL, NULL, PRIORITY, 0, 0);
int main(void)
{
while (1) {
printk("main alive\n");
k_msleep(1000);
}
return 0;
}CONFIG_PRINTK=yThe macro arguments are the thread's name, stack size, entry function, three parameters, priority, option flags and a start delay in milliseconds. Here the delay of 0 starts it immediately. The entry function always takes three void * parameters, whether you use them or not. Built for any board, the console shows the two threads taking turns. The exact interleaving depends on timing, and a typical start is:
*** Booting Zephyr OS build v4.2.0 ***
main alive
blinker 0
blinker 1
main alive
blinker 2
blinker 3main() is itself a thread, created by the kernel with its own priority, set by CONFIG_MAIN_THREAD_PRIORITY (default 0 on most builds, which is the first preemptible priority). That detail matters when you choose a priority for yours.
Creating threads at run time
K_THREAD_DEFINE fixes the thread at build time. When you need to start a thread under program control, use k_thread_create, with a stack defined by K_THREAD_STACK_DEFINE:
#include <zephyr/kernel.h>
K_THREAD_STACK_DEFINE(worker_stack, 1024);
static struct k_thread worker_data;
static void worker(void *p1, void *p2, void *p3)
{
int id = (int)(intptr_t)p1;
printk("worker %d running\n", id);
}
int main(void)
{
k_tid_t tid = k_thread_create(&worker_data, worker_stack,
K_THREAD_STACK_SIZEOF(worker_stack),
worker, (void *)(intptr_t)7, NULL, NULL,
5, 0, K_NO_WAIT);
k_thread_name_set(tid, "worker");
k_thread_join(tid, K_FOREVER);
printk("worker finished\n");
return 0;
}*** Booting Zephyr OS build v4.2.0 ***
worker 7 running
worker finishedk_thread_create takes the control block, the stack and its size, the entry function and parameters, priority, options and a start delay, and returns a thread id. k_thread_name_set helps debuggers and the thread analyzer, and it needs CONFIG_THREAD_NAME=y. k_thread_join waits for the thread to exit, and it works for threads created with k_thread_create. A thread ends when its entry function returns, and its stack can then be reused.
Priorities: preemptive and cooperative
Zephyr threads come in two kinds, and the number decides which:
| Priority range | Kind | Behavior |
|---|---|---|
Negative, from -CONFIG_NUM_COOP_PRIORITIES to -1 | Cooperative | Never preempted by another thread. Runs until it blocks or yields |
0 to CONFIG_NUM_PREEMPT_PRIORITIES - 1 | Preemptible | Can be preempted by a higher-priority thread at any time |
A cooperative thread keeps the CPU until it calls something that blocks, such as k_sleep, or calls k_yield. Interrupts can still run, but no other thread does. Use cooperative priorities sparingly, for short critical stretches where you know the code finishes quickly, or for threads that implement a driver's internal sequencing. Most application threads are preemptible, with priorities between 5 and 15 so there is room above and below.
Lower numbers win. A thread at priority 2 preempts a thread at priority 10. The idle thread runs when nothing else is ready, at the lowest priority.
The scheduler also supports time slicing among equal-priority preemptible threads, enabled with CONFIG_TIMESLICING=y and CONFIG_TIMESLICE_SIZE. Without it, equal-priority threads take turns only when one blocks.
What a thread can be doing
A thread is in one of these states, and the scheduler only chooses among the ready ones:
| State | Meaning | How it leaves |
|---|---|---|
| Ready | Can run, waiting for the CPU | Scheduler selects it |
| Running | Has the CPU | Preempted, blocks, yields or exits |
| Pending | Waiting on a kernel object, such as a semaphore | The object is signaled or the wait times out |
| Sleeping | Waiting for a time to pass | The timeout expires |
| Suspended | Stopped with k_thread_suspend | k_thread_resume |
| Dead | Finished | Not applicable |
Waiting is the central idea. A thread that has nothing to do should be pending or sleeping, never spinning, because a spinning thread wastes the CPU and, at a high priority, starves everything below it. The wait calls all take a timeout, written with K_NO_WAIT, K_FOREVER or a duration such as K_MSEC(100) and K_SECONDS(2).
Two calls to know: k_msleep(ms) and k_sleep(K_SECONDS(1)) sleep for a time, and k_yield() gives up the rest of the current slice to another ready thread of the same priority. Avoid k_busy_wait(us), which spins and is for sub-millisecond hardware delays only.
Sizing stacks
A stack that is too small corrupts memory silently or faults, and one that is too large wastes RAM. Zephyr gives you tools to measure instead of guess. Enable the thread analyzer:
CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_AUTO=y
CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=5
CONFIG_THREAD_NAME=y
CONFIG_INIT_STACKS=yIt prints a report at the chosen interval with each thread's stack use:
Thread analyze:
blinker : STACK: unused 760 usage 264 / 1024 (25 %); CPU: 0 %
main : STACK: unused 1728 usage 320 / 2048 (15 %); CPU: 1 %
idle : STACK: unused 280 usage 40 / 320 (12 %); CPU: 98 %The numbers are examples for a small build. Read them as: "this thread has used at most 264 bytes of its 1024." Leave a margin, because the figure is a high-water mark from the code paths that actually ran. Enabling CONFIG_HW_STACK_PROTECTION=y on chips with a memory protection unit turns an overflow into a clean fault instead of corruption, and a later post in this group covers it.
Timers
A thread should not poll the clock. For periodic or one-shot actions, use a kernel timer, k_timer. It calls a function when it expires, from the system clock interrupt context, so the handler must be short and non-blocking:
#include <zephyr/kernel.h>
static void tick(struct k_timer *timer)
{
printk("tick\n");
}
K_TIMER_DEFINE(tick_timer, tick, NULL);
int main(void)
{
k_timer_start(&tick_timer, K_SECONDS(1), K_SECONDS(1));
k_sleep(K_SECONDS(4));
k_timer_stop(&tick_timer);
return 0;
}*** Booting Zephyr OS build v4.2.0 ***
tick
tick
tick
tickk_timer_start(timer, duration, period) runs the handler after duration, then every period. A period of K_NO_WAIT makes it one-shot. Anything slow belongs in a thread, which the handler wakes with a semaphore or by submitting work, as the next sections show.
Semaphores: signal and count
A semaphore holds a count. k_sem_give increments it and wakes a waiting thread, and k_sem_take decrements it, blocking when the count is zero. It is the right tool for signaling "something happened":
#include <zephyr/kernel.h>
K_SEM_DEFINE(data_ready, 0, 1);
static void consumer(void *a, void *b, void *c)
{
while (1) {
k_sem_take(&data_ready, K_FOREVER);
printk("consumer woke\n");
}
}
K_THREAD_DEFINE(cons, 1024, consumer, NULL, NULL, NULL, 5, 0, 0);
int main(void)
{
for (int i = 0; i < 3; i++) {
k_msleep(500);
k_sem_give(&data_ready);
}
return 0;
}*** Booting Zephyr OS build v4.2.0 ***
consumer woke
consumer woke
consumer wokeK_SEM_DEFINE(name, initial, limit) creates the semaphore at build time. The limit of 1 makes it a binary semaphore: extra gives beyond the limit are ignored. A larger limit makes it a counting semaphore, useful for counting free resources or queued events. A semaphore may be given from an interrupt handler, which makes it the standard bridge from interrupt context to a thread. It has no owner, so any thread or ISR may give, and that is the main difference from a mutex.
Mutexes: protect shared data
A mutex guards a critical section. The thread that locks it must unlock it, and while it holds the lock, other threads that try to lock it block:
#include <zephyr/kernel.h>
K_MUTEX_DEFINE(stats_lock);
static int total;
static void add_sample(int v)
{
k_mutex_lock(&stats_lock, K_FOREVER);
total += v;
k_mutex_unlock(&stats_lock);
}Zephyr mutexes support priority inheritance: when a high-priority thread waits on a mutex held by a low-priority thread, the holder temporarily runs at the waiter's priority, so a medium-priority thread cannot keep the holder from finishing. This prevents unbounded priority inversion, a classic bug where a high-priority thread is blocked for an unpredictable time. Semaphores do not do this, which is one reason to use a mutex, not a semaphore, for mutual exclusion. Mutexes also cannot be used from an ISR, since there is no thread to own them.
Message queues: pass data safely
When threads must exchange data, not just signal, a message queue copies fixed-size messages from producer to consumer and blocks either side when it cannot proceed:
#include <zephyr/kernel.h>
struct sample {
int id;
int value;
};
K_MSGQ_DEFINE(sample_q, sizeof(struct sample), 8, 4);
static void reader(void *a, void *b, void *c)
{
struct sample s;
while (1) {
k_msgq_get(&sample_q, &s, K_FOREVER);
printk("got %d: %d\n", s.id, s.value);
}
}
K_THREAD_DEFINE(rd, 1024, reader, NULL, NULL, NULL, 5, 0, 0);
int main(void)
{
for (int i = 0; i < 3; i++) {
struct sample s = { .id = i, .value = i * 10 };
k_msgq_put(&sample_q, &s, K_NO_WAIT);
k_msleep(100);
}
return 0;
}*** Booting Zephyr OS build v4.2.0 ***
got 0: 0
got 1: 10
got 2: 20K_MSGQ_DEFINE(name, msg_size, max_msgs, align) creates a queue holding up to eight messages of that size, aligned to four bytes. k_msgq_put copies the message in, and k_msgq_get copies it out. A full queue makes the put fail with -ENOMSG for K_NO_WAIT, or wait if you pass a timeout. Because messages are copied, there are no ownership questions, and the queue is safe to use from an ISR with K_NO_WAIT. A dedicated post covers it in depth.
Work queues: defer work out of interrupts
A work queue is a thread that runs submitted work items one by one. It is the standard way to move work out of an interrupt handler or timer callback without creating a thread per task:
#include <zephyr/kernel.h>
static void process(struct k_work *work)
{
printk("processing in the system workqueue\n");
}
K_WORK_DEFINE(my_work, process);
static void isr_like(struct k_timer *t)
{
k_work_submit(&my_work);
}
K_TIMER_DEFINE(t, isr_like, NULL);
int main(void)
{
k_timer_start(&t, K_MSEC(200), K_NO_WAIT);
k_msleep(500);
return 0;
}*** Booting Zephyr OS build v4.2.0 ***
processing in the system workqueuek_work_submit places the item on the system work queue, a built-in thread with its own stack and priority, and the handler runs there. The handler may block briefly, but it holds up other work items on the same queue while it does. Later posts cover delayed work, cancellation and dedicated queues.
Events and condition-style waiting
Sometimes a thread must wait for any of several conditions, or for a combination. Zephyr's event objects hold a 32-bit mask. One side posts bits, and the other waits for a chosen subset:
#include <zephyr/kernel.h>
#define EVT_RX_DONE BIT(0)
#define EVT_TX_DONE BIT(1)
#define EVT_ERROR BIT(2)
K_EVENT_DEFINE(io_events);
static void waiter(void *a, void *b, void *c)
{
while (1) {
uint32_t got = k_event_wait(&io_events, EVT_RX_DONE | EVT_ERROR,
true, K_FOREVER);
if (got & EVT_ERROR) {
printk("error\n");
}
if (got & EVT_RX_DONE) {
printk("rx done\n");
}
}
}
K_THREAD_DEFINE(w, 1024, waiter, NULL, NULL, NULL, 5, 0, 0);
int main(void)
{
k_msleep(100);
k_event_post(&io_events, EVT_RX_DONE);
k_msleep(100);
k_event_post(&io_events, EVT_ERROR);
return 0;
}*** Booting Zephyr OS build v4.2.0 ***
rx done
errork_event_wait(event, mask, reset, timeout) returns the bits that matched, and with reset true it clears the event's bits before waiting, so stale events from before do not wake it. k_event_wait_all waits until every bit in the mask is set. Events are cheap and suit state machines where several sources feed one thread. They carry no data, so pair them with a queue when a payload is needed. The wait for several different object types at once is the subject of the k_poll post later in this group.
FIFOs, LIFOs and pipes
Message queues copy fixed-size messages. Two other kernel objects pass data by pointer, which avoids the copy and allows variable sizes. k_fifo and k_lifo are lists of items that you allocate yourself, where the first word of each item is reserved for the kernel's link:
#include <zephyr/kernel.h>
struct packet {
void *fifo_reserved;
uint8_t len;
uint8_t data[16];
};
K_FIFO_DEFINE(rx_fifo);
K_HEAP_DEFINE(pkt_heap, 1024);
static void producer_step(uint8_t first)
{
struct packet *p = k_heap_alloc(&pkt_heap, sizeof(*p), K_NO_WAIT);
if (p == NULL) {
return;
}
p->len = 1;
p->data[0] = first;
k_fifo_put(&rx_fifo, p);
}
static void consumer_step(void)
{
struct packet *p = k_fifo_get(&rx_fifo, K_FOREVER);
printk("packet len %u first %u\n", p->len, p->data[0]);
k_heap_free(&pkt_heap, p);
}The consumer owns the item after k_fifo_get, and must free it. That is the price of pointer passing: the ownership rules are yours to keep. k_fifo returns items in the order they were put, and k_lifo returns the most recent first. Use a message queue when messages are small and fixed in size, since it needs no allocator. Use a FIFO when messages are large or vary. A third object, k_pipe, passes a byte stream between threads, useful for ports and serial data, and later releases changed its API, so read the documentation of your release before using it.
Time slicing and equal priorities
Without time slicing, equal-priority preemptible threads run until they block. A thread that loops without blocking, such as a polling loop, then keeps the CPU from its equal-priority peers forever. Turn on slicing to share the CPU among them:
CONFIG_TIMESLICING=y
CONFIG_TIMESLICE_SIZE=10
CONFIG_TIMESLICE_PRIORITY=0CONFIG_TIMESLICE_SIZE is the slice in milliseconds, and CONFIG_TIMESLICE_PRIORITY is the priority at and below which slicing applies, so threads more urgent than that value are never sliced. Time slicing is a fairness tool, not a real-time one. A product with deadlines should put urgent work at distinct, higher priorities and keep slicing for background threads.
Interrupts and threads together
An interrupt service routine runs on its own stack and preempts any thread. It must be short, and it must not block. The standard pattern is to do the minimum in the ISR, then hand off:
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
static const struct gpio_dt_spec btn = GPIO_DT_SPEC_GET(DT_ALIAS(sw0), gpios);
static struct gpio_callback btn_cb;
K_SEM_DEFINE(button_sem, 0, 1);
static void button_isr(const struct device *dev, struct gpio_callback *cb,
uint32_t pins)
{
k_sem_give(&button_sem);
}
static void button_thread(void *a, void *b, void *c)
{
while (1) {
k_sem_take(&button_sem, K_FOREVER);
printk("button pressed\n");
}
}
K_THREAD_DEFINE(btn_tid, 1024, button_thread, NULL, NULL, NULL, 6, 0, 0);
int main(void)
{
gpio_pin_configure_dt(&btn, GPIO_INPUT);
gpio_pin_interrupt_configure_dt(&btn, GPIO_INT_EDGE_TO_ACTIVE);
gpio_init_callback(&btn_cb, button_isr, BIT(btn.pin));
gpio_add_callback(btn.port, &btn_cb);
return 0;
}The ISR gives a semaphore, and the thread does the printing, which can block on the console. Every press wakes the thread once, as long as it is waiting when the next press happens. If presses can come faster than the thread processes them, a binary semaphore loses counts, and a counting semaphore or a queue is the right object.
Do not share data between an ISR and a thread with a mutex. For small values, use atomic operations from <zephyr/sys/atomic.h>, or disable interrupts for a few instructions with irq_lock() and irq_unlock(). For anything bigger, copy it through a queue, which is safe to put to from an ISR with K_NO_WAIT.
A complete pipeline
Put the pieces together in a small program: a timer samples a fake sensor, an ISR-like handler pushes the reading into a queue, and a processing thread averages and reports under a mutex-protected statistics structure.
#include <zephyr/kernel.h>
struct reading {
int32_t value;
};
K_MSGQ_DEFINE(readings_q, sizeof(struct reading), 16, 4);
K_MUTEX_DEFINE(stats_lock);
static struct {
int64_t sum;
uint32_t count;
} stats;
static int32_t fake_adc;
static void sample_timer(struct k_timer *t)
{
struct reading r = { .value = fake_adc };
fake_adc += 3;
if (k_msgq_put(&readings_q, &r, K_NO_WAIT) != 0) {
/* queue full: drop the sample */
}
}
K_TIMER_DEFINE(sampler, sample_timer, NULL);
static void processor(void *a, void *b, void *c)
{
struct reading r;
while (1) {
k_msgq_get(&readings_q, &r, K_FOREVER);
k_mutex_lock(&stats_lock, K_FOREVER);
stats.sum += r.value;
stats.count++;
k_mutex_unlock(&stats_lock);
}
}
K_THREAD_DEFINE(proc, 1024, processor, NULL, NULL, NULL, 5, 0, 0);
int main(void)
{
k_timer_start(&sampler, K_MSEC(100), K_MSEC(100));
for (int i = 0; i < 3; i++) {
k_msleep(1000);
k_mutex_lock(&stats_lock, K_FOREVER);
printk("count %u average %lld\n", stats.count,
stats.count ? stats.sum / stats.count : 0);
k_mutex_unlock(&stats_lock);
}
return 0;
}The three printed lines show the count and average after one, two and three seconds. With a 100 ms period the first line follows roughly nine or ten samples:
*** Booting Zephyr OS build v4.2.0 ***
count 9 average 12
count 19 average 27
count 29 average 42The exact counts depend on when the timer starts relative to the first print, and the averages follow from the fake ADC counting up by 3. Each role uses the right primitive. The timer handler runs in interrupt context, so it uses a non-blocking k_msgq_put. The processor thread blocks on the queue and holds the mutex only while updating the shared sums. main() takes the same mutex to read a consistent pair of sum and count, so it never sees a count that does not match the sum.
Choosing a primitive
| You want to | Use | Notes |
|---|---|---|
| Signal that something happened | Semaphore | Works from an ISR with k_sem_give |
| Protect shared data in threads | Mutex | Priority inheritance, not for ISRs |
| Send small fixed-size messages | Message queue | Copies data, safe from an ISR with K_NO_WAIT |
| Send large or variable items | FIFO or LIFO | Pointer passing, you manage memory |
| Wait for any of several conditions | Events or k_poll | Events carry bits only |
| Run code later or off an interrupt | Work queue | Handlers share a thread |
| Run code on a schedule | Timer, or delayable work | Timer handler runs in interrupt context |
| Share a counter or flag between ISR and thread | Atomic operations | Cheapest, limited to simple values |
When two primitives fit, prefer the one that says more. A queue says "data flows this way", and a semaphore says only "something happened". Code that reads like its intent has fewer bugs.
Diagnosing the classic failures
Deadlock. Two threads each hold a mutex the other wants. Both sit pending forever, and the system otherwise keeps running. Avoid it by always taking multiple locks in the same order, holding them briefly, and using timeouts such as K_MSEC(100) with an error path instead of K_FOREVER in code that must recover. A debugger's thread list shows two threads pending on mutexes, and the mutex owner fields show the cycle.
Priority inversion. A high-priority thread waits on a resource held by a low-priority thread, which is preempted by a medium one. Use mutexes, not semaphores, for exclusion, so inheritance applies, and keep critical sections short.
Starvation. A high-priority thread that never blocks keeps lower ones from running at all, including the idle thread, which may disable power saving. Make every loop block on something.
Lost wakeups. A binary semaphore given twice before the consumer runs counts once. If every event matters, use a counting semaphore or a queue.
Stack overflow. Symptoms are random crashes in unrelated code. Check the thread analyzer, raise the stack, and turn on CONFIG_HW_STACK_PROTECTION=y.
Using a blocking call in an ISR. On debug builds with CONFIG_ASSERT=y, Zephyr asserts when a blocking function is called from an ISR with a nonzero timeout. Fix it by deferring the work.
Where this guide stops
This guide is about the kernel's native primitives on a single core. Four areas lie outside it.
Multicore systems. With symmetric multiprocessing enabled, several threads run at once and shared data needs spinlocks, k_spinlock, in addition to the primitives above. Mutexes and semaphores still work, and the rules about ISRs get stricter.
POSIX and other APIs. Zephyr offers a POSIX threads layer for porting code, with the usual pthread_* calls built on the same kernel. Native APIs are lighter, and the POSIX layer is the right choice for porting existing code.
Safety certification. A product with functional safety requirements needs a qualified subset and process, beyond this guide.
Higher-level messaging. For decoupled modules that publish and subscribe, the zbus message bus builds on these primitives, and the post that compares queues, FIFOs and zbus helps choose.
The posts in this group cover each primitive in depth, in the order a project meets them: creating threads, priorities, timers, work queues, message queues, mutexes and semaphores, stack protection, cancelling work, passing data, ISR-safe code, k_poll and dedicated work queues.
Timeouts and time units
Every blocking call takes a k_timeout_t, a value that says how long to wait. Understanding the type removes a whole class of surprises. The constructors are macros:
| Macro | Meaning |
|---|---|
K_NO_WAIT | Do not block. Return at once, with an error if the operation cannot complete |
K_FOREVER | Block until the operation can complete |
K_MSEC(n), K_SECONDS(n), K_USEC(n) | A relative duration, converted to kernel ticks |
K_TICKS(n) | A duration in raw ticks |
K_TIMEOUT_ABS_MS(t) | An absolute point in time, in milliseconds of uptime |
The kernel counts time in ticks, set by CONFIG_SYS_CLOCK_TICKS_PER_SEC. On many boards that is a value like 32768 for a low-frequency clock or 10000 for a fast one. A duration smaller than one tick rounds up, so K_USEC(10) may wait a whole tick. The practical consequences are that sleeping for one millisecond is accurate to the tick, and that sub-tick delays need k_busy_wait, which spins.
The return value of a blocking call tells you what happened. Semaphores, mutexes and queues return zero on success, -EBUSY when K_NO_WAIT found the object unavailable, and -EAGAIN when a timeout expired. Treat the timeout path as a normal case. A thread that can wait forever on an object nobody will signal is a hang, and a thread with a timeout can log the problem and recover.
To measure elapsed time, use k_uptime_get() for milliseconds since boot or k_cycle_get_32() for hardware cycles, and convert with k_cyc_to_us_floor32. Do not compute durations by counting loop iterations.
What the scheduler does internally
The kernel keeps ready threads in a data structure chosen at build time. Three options exist, and they matter once you have many threads:
| Option | Structure | Best for |
|---|---|---|
CONFIG_SCHED_DUMB | One linked list sorted by priority | Few threads, smallest code |
CONFIG_SCHED_SCALABLE | A balanced tree | Many threads at many priorities |
CONFIG_SCHED_MULTIQ | One list per priority and a bitmap | Many threads, few distinct priorities |
The default is the simple list, and it is fine for dozens of threads. Switch only if you have measured scheduling cost on a system with hundreds of ready threads, and read the option's help text in menuconfig.
Whatever the structure, the rule is the same: the highest-priority ready thread runs. A reschedule happens at defined points: when a thread blocks, when it makes a higher-priority thread ready by giving a semaphore or posting to a queue, when a timer or interrupt wakes a thread, and when a thread calls k_yield. A cooperative thread, or code inside a k_sched_lock() section, defers the reschedule until it ends.
k_sched_lock() and k_sched_unlock() stop other threads from preempting the current one without disabling interrupts. Use the pair around a few instructions that must not be interleaved with other threads, and never block inside it. Interrupts still run, so an ISR may still touch the data, which is why this is a poor substitute for a mutex when an ISR is involved.
Thread options, data and lifecycle
The options argument of thread creation takes flags:
| Flag | Effect |
|---|---|
K_ESSENTIAL | If this thread aborts, the system halts. For threads whose death is a fatal error |
K_FP_REGS | Save floating point registers on context switch, needed if the thread uses the FPU on chips that need explicit marking |
K_USER | Run in user mode, with memory protection, when user mode is enabled |
K_INHERIT_PERMS | Give the new user thread the creator's kernel object permissions |
A thread can carry a pointer for its own use with k_thread_custom_data_set and k_thread_custom_data_get, enabled by CONFIG_THREAD_CUSTOM_DATA. With CONFIG_THREAD_LOCAL_STORAGE and the __thread keyword you get ordinary thread-local variables. Use these for per-thread context such as a transaction id, not for communication.
Other control calls change a thread after it starts. k_thread_priority_set(tid, prio) changes its priority, which is useful to raise a thread during a critical period and restore it after. k_thread_suspend and k_thread_resume stop and restart it, and k_thread_abort ends it immediately. Aborting a thread that holds a mutex leaves the mutex locked and is almost always a bug, so prefer a flag that the thread checks and a clean return, then k_thread_join to wait for it. A thread that returns from its entry function is already finished and need not be aborted.
For a delayed start, pass a delay instead of K_NO_WAIT, as K_MSEC(500), and the thread begins after that time. k_thread_start starts a thread created with K_FOREVER as its delay. This is a clean way to create threads at boot and start them in a chosen order once the system is ready.
Condition variables for state changes
A mutex protects data, and a thread often needs to wait until that data reaches some state. A semaphore can encode a single condition, and a condition variable handles an arbitrary one. The classic example is a bounded buffer. The consumer waits for "not empty" while holding the mutex, the producer signals after adding an item:
#include <zephyr/kernel.h>
K_MUTEX_DEFINE(buf_lock);
K_CONDVAR_DEFINE(not_empty);
static int items;
static void produce(void)
{
k_mutex_lock(&buf_lock, K_FOREVER);
items++;
k_condvar_signal(¬_empty);
k_mutex_unlock(&buf_lock);
}
static void consume(void)
{
k_mutex_lock(&buf_lock, K_FOREVER);
while (items == 0) {
k_condvar_wait(¬_empty, &buf_lock, K_FOREVER);
}
items--;
k_mutex_unlock(&buf_lock);
}k_condvar_wait releases the mutex while waiting and reacquires it before returning, and the while loop rechecks the condition because a wakeup does not guarantee the condition still holds. Use a condition variable when the condition involves several fields of shared state. For a single count, a semaphore is simpler and cheaper, and for data flow, a queue removes the shared state entirely, which is the best fix.
Atomics and spinlocks
Two lighter tools exist for tiny critical sections. Atomic operations, declared in <zephyr/sys/atomic.h>, perform a read-modify-write as one step:
#include <zephyr/sys/atomic.h>
static atomic_t rx_count = ATOMIC_INIT(0);
void on_receive(void)
{
atomic_inc(&rx_count);
}
int report(void)
{
return atomic_get(&rx_count);
}atomic_inc, atomic_add, atomic_set_bit and atomic_test_and_clear_bit work from any context, including ISRs, and need no lock. They fit counters and flags. They cannot protect a structure of several fields.
A spinlock, k_spinlock, disables interrupts on the current CPU and, on multiprocessor builds, spins on a flag shared by all CPUs:
#include <zephyr/kernel.h>
static struct k_spinlock lock;
static uint32_t shared_a, shared_b;
void update(uint32_t a, uint32_t b)
{
k_spinlock_key_t key = k_spin_lock(&lock);
shared_a = a;
shared_b = b;
k_spin_unlock(&lock, key);
}Use spinlocks only for very short sections, with no blocking and no calls into code that might block, because interrupts are off for the duration. They are the right tool when an ISR and a thread must update the same small structure, since a mutex cannot be taken in an ISR. The key returned by k_spin_lock carries the previous interrupt state and must be passed back to the unlock.
Memory shared between threads
Threads share one address space, and the question is who owns each buffer. Three patterns cover most code.
Static buffers owned by one thread. The simplest rule: one thread writes a structure and others only see copies passed in messages.
Memory slabs. K_MEM_SLAB_DEFINE(name, block_size, count, align) creates a pool of fixed-size blocks with constant-time allocation and no fragmentation. A producer allocates a block with k_mem_slab_alloc, fills it, and sends the pointer through a queue. The consumer frees it with k_mem_slab_free. Allocation is safe from an ISR with K_NO_WAIT.
Heaps. k_heap_alloc and k_malloc give variable sizes, with fragmentation as the price, so avoid them in long-running systems that must not run out of memory. If you use a heap, size it with CONFIG_HEAP_MEM_POOL_SIZE or a K_HEAP_DEFINE, and check every allocation result.
A memory slab fits the earlier FIFO example better than a heap, since packets have a bounded size and a known count. Choose the pool size from the worst case of how many items can be in flight at once.
Choosing priorities for a real design
Assigning priorities is a design task, and a few rules of thumb produce sound systems.
Rank by deadline, not by importance. A thread whose work must finish within 2 ms needs a higher priority than one with a 200 ms deadline, even if the slow one matters more. This is the rate-monotonic idea: shorter period, higher priority.
Keep high-priority threads short and blocked most of the time. They should wake, do bounded work and block again. Long computations belong at low priority.
Give worker threads distinct priorities when their order matters, and equal ones when it does not.
Put the main thread somewhere sensible. By default
main()runs at a priority near the middle. If it only supervises, it can stay there.Reserve cooperative priorities for code that must not be preempted, and keep it short.
Never let a high-priority thread wait on a low-priority one without priority inheritance, and prefer mutexes over semaphores for exclusion.
A typical small system might use priority 2 for a thread that services a communications peripheral, 5 for the sensor pipeline, 8 for the main application logic, and 12 for logging and housekeeping. The system work queue defaults to a negative, cooperative priority on some configurations, set by CONFIG_SYSTEM_WORKQUEUE_PRIORITY, so check what it is in your build, since it affects every work item.
Observing and tracing a running system
Two kinds of tool show what threads are doing. The thread analyzer, shown earlier, reports stack and CPU use. For events over time, Zephyr's tracing subsystem hooks the kernel and emits records for context switches, semaphore operations and ISR entry and exit. Enable CONFIG_TRACING=y and pick a format and backend, for example CONFIG_TRACING_CTF for the Common Trace Format over UART or CONFIG_SEGGER_SYSTEMVIEW for SEGGER's viewer over RTT. A timeline view makes priority inversion and starvation obvious in a way a log cannot, because you see which thread held the CPU at every moment. Tracing costs CPU and RAM, so use it as a diagnostic build option, and see the tracing documentation for each backend's settings.
The shell can list threads at run time too. With CONFIG_SHELL=y and CONFIG_KERNEL_SHELL=y, the command kernel threads prints each thread's name, priority, state and stack use, which is often enough to find a thread stuck pending:
uart:~$ kernel threads
Scheduler: 25 since last call
Threads:
0x20000a68 blinker
options: 0x0, priority: 5 timeout: 0
state: pending, entry: 0x1a2c
stack size 1024, unused 760, usage 264 / 1024 (25 %)The addresses and numbers are examples. A thread in the pending state with no timeout is waiting for an object, and the next step is to find which object by looking at the code at the entry point.
Testing concurrent code
Concurrency bugs depend on timing, so test in an environment that makes timing controllable. The native_sim board runs your threads with simulated time, so a test can advance the clock by thousands of seconds in a moment and exercise a rare ordering many times. Write ztest cases that start the threads, send messages and check results, and run them under Twister, as described in the posts on native_sim and Twister. Add CONFIG_ASAN=y there to catch memory errors in code that shares buffers. For ordering bugs, vary thread priorities and sleep durations in the test and run it with several seeds.
On hardware, soak tests that run for hours with logging catch the rare deadlocks. Add a watchdog that resets the board when a thread stops checking in, so the failure is recorded and recovery is automatic.
Three practice tasks
Do these in order. Each has an observable result.
Two threads, one counter. Create two threads that each increment a shared integer 100,000 times with no lock, and print the total from
main()after joining both. The result is below 200,000 on a preemptive system because increments interleave. Add a mutex and confirm the total is exactly 200,000. Replace the mutex withatomic_incand compare.Producer and consumer with backpressure. Use a queue of depth 4. Make the producer faster than the consumer and check what
k_msgq_putreturns withK_NO_WAITversusK_FOREVER. Decide which is correct for a sensor that must never block.Cause and fix a priority inversion. Create three threads at priorities 3, 6 and 9, where the low one takes a mutex and the high one wants it, and the medium one spins briefly. Use a semaphore with initial count 1 instead of a mutex and watch the high-priority thread wait for the medium one. Switch to a mutex and see the inheritance fix it, with timestamps from
k_uptime_get().
Reading the kernel source
Zephyr's kernel is small enough to read. The scheduler is kernel/sched.c, threads are kernel/thread.c, semaphores kernel/sem.c, mutexes kernel/mutex.c and queues kernel/msg_q.c. Each file is a few hundred lines, and the functions you call map directly to the code. When documentation leaves a question open, such as what exactly k_sem_give does to a waiter's priority, the source answers it for your release.


