Zephyr Threads on ESP32-S3: Priorities and the Scheduler
Run two Zephyr threads on the ESP32-S3 with K_THREAD_DEFINE and k_thread_create. Set priorities, turn on time slicing and stop a busy loop starving threads.

In the last post we blinked an external LED on GPIO 4. The pin came from an app.overlay, and everything ran inside main(). In the first Zephyr post I said an RTOS lets you split work into threads, and the kernel decides which one runs.
This time we do that for real. The LED gets its own thread. A second thread prints a short report every two seconds. Then we look at stacks and priorities, and at what the scheduler does while both threads sleep. At the end we break it on purpose with a loop that never sleeps, so you can see what starving a thread looks like on the board.
What you need
You need the same setup as the last post. Your Zephyr workspace and west should already work, and the ESP32-S3-DevKitC should be on the UART port. Keep the external LED and its resistor on GPIO 4. The build target is still esp32s3_devkitc/esp32s3/procpu.
Our course uses Zephyr 4.1. This app builds for esp32s3_devkitc/esp32s3/procpu on Zephyr 4.1 and on Zephyr 4.5, the current release, with no warnings on either. The thread APIs in this post are the same in both. One default changed between them, and I point it out in the prj.conf section.
The output lines in this post come from running the same code in QEMU's Xtensa emulator, which uses the same kind of CPU core as the ESP32-S3. On the board the milliseconds and byte counts will be a little different, but the pattern is the same.
What a thread is in Zephyr
A thread is a function that the kernel runs on its own. It has its own stack, so its local variables do not mix with the locals of other threads. The kernel also keeps a small control block for each thread, a struct k_thread. That is how it keeps track of the thread and knows where to pick it up again.
Each thread has a priority. The kernel's scheduler uses it to pick which ready thread gets the CPU. You can also give a thread a start delay, so it begins a little after boot.
The entry function always looks like this:
void my_thread(void *p1, void *p2, void *p3);
The three pointers are arguments you can pass in when you create the thread. In this post we pass NULL for all of them.
main() is also a thread. Zephyr starts it after the kernel is up. When main() returns, that thread ends, but the other threads keep running. That is a big change from a bare-metal loop, where returning from main() usually means the program is finished.
Create the app folder
Make a new app next to the last one, for example zephyrproject/app/threads_blink:
threads_blink/
├── CMakeLists.txt
├── app.overlay
├── prj.conf
└── src
└── main.c
In PowerShell:
cd $Env:HOMEPATH\zephyrproject
mkdir app\threads_blink\src
On Linux or macOS, use mkdir -p ~/zephyrproject/app/threads_blink/src.
CMakeLists.txt is the same as before, with a new project name:
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr)
project(threads_blink)
target_sources(app PRIVATE src/main.c)
Copy app.overlay from the blink app without any change. It gives us the led0 alias on GPIO 4:
/ {
aliases {
led0 = &ext_led;
};
leds {
compatible = "gpio-leds";
ext_led: led_0 {
gpios = <&gpio0 4 GPIO_ACTIVE_HIGH>;
};
};
};
prj.conf has a few more lines this time:
CONFIG_GPIO=y
CONFIG_THREAD_NAME=y
CONFIG_TIMESLICING=y
CONFIG_TIMESLICE_SIZE=10
CONFIG_TIMESLICE_PRIORITY=0
CONFIG_THREAD_NAME lets threads carry a name. Debug tools and crash messages then show report instead of only an address.
The three time slicing lines need a short note. CONFIG_TIMESLICING is already on by default. CONFIG_TIMESLICE_SIZE is how long, in milliseconds, a thread can run before another ready thread of the same priority gets a turn. In Zephyr 4.1 the default size is 0, which means no limit, so time slicing is on but does nothing. From Zephyr 4.2 the default is 20 ms. I set it to 10 so the app behaves the same on both versions. CONFIG_TIMESLICE_PRIORITY=0 means every preemptive thread can be sliced. I explain slicing properly further down.
The full main.c
Put this in src/main.c:
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/sys/printk.h>
#define LED0_NODE DT_ALIAS(led0)
#define BLINK_STACK_SIZE 1024
#define REPORT_STACK_SIZE 1024
#define BLINK_PRIORITY 5
#define REPORT_PRIORITY 7
#define BLINK_PERIOD_MS 500
#define REPORT_PERIOD_MS 2000
/* Set to 1 to add a thread that never sleeps (see "A common mistake") */
#define RUN_BUSY_DEMO 0
#define BUSY_PRIORITY 4
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
/* Written by the blink thread, read by the report thread */
static atomic_t toggles;
/* Thread 1: created at build time with K_THREAD_DEFINE */
static void blink_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
if (!gpio_is_ready_dt(&led)) {
printk("blink: LED GPIO is not ready\n");
return;
}
if (gpio_pin_configure_dt(&led, GPIO_OUTPUT_INACTIVE) < 0) {
printk("blink: failed to configure the LED pin\n");
return;
}
while (1) {
gpio_pin_toggle_dt(&led);
atomic_inc(&toggles);
k_msleep(BLINK_PERIOD_MS);
}
}
K_THREAD_DEFINE(blink_tid, BLINK_STACK_SIZE, blink_thread,
NULL, NULL, NULL, BLINK_PRIORITY, 0, 0);
/* Thread 2: created at run time from main() with k_thread_create */
K_THREAD_STACK_DEFINE(report_stack, REPORT_STACK_SIZE);
static struct k_thread report_data;
static void report_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
while (1) {
printk("[%u ms] report: LED toggled %ld times\n",
k_uptime_get_32(), (long)atomic_get(&toggles));
k_msleep(REPORT_PERIOD_MS);
}
}
#if RUN_BUSY_DEMO
/* A thread that never sleeps. It starts 5 seconds after boot. */
static void busy_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
printk("busy: starting a loop that never sleeps\n");
while (1) {
k_busy_wait(1000); /* spin for 1 ms without giving up the CPU */
}
}
K_THREAD_DEFINE(busy_tid, 1024, busy_thread,
NULL, NULL, NULL, BUSY_PRIORITY, 0, 5000);
#endif
int main(void)
{
k_tid_t report_tid;
report_tid = k_thread_create(&report_data, report_stack,
K_THREAD_STACK_SIZEOF(report_stack),
report_thread, NULL, NULL, NULL,
REPORT_PRIORITY, 0, K_NO_WAIT);
k_thread_name_set(report_tid, "report");
printk("main: priority %d, report thread started, main returns now\n",
k_thread_priority_get(k_current_get()));
return 0;
}
The blink thread is the loop from the last post, moved into its own function. It toggles the LED, adds one to a counter, and sleeps for 500 ms. The report thread wakes every two seconds and prints the uptime and the counter. main() starts the report thread and then returns.
The counter is an atomic_t. One thread writes it and another reads it. atomic_inc and atomic_get make each read and write happen in one step, so the report thread never sees half an update. For anything bigger than a counter you would use a mutex or a message queue. We will get to those in a later post.
Two ways to create a thread
The blink thread uses K_THREAD_DEFINE. This macro sets up everything at build time. It makes the stack, the struct k_thread and a thread id called blink_tid, and the kernel starts the thread during boot. The arguments are, in order: the id name, the stack size in bytes, the entry function, the three arguments, the priority, the options and the start delay. Options are 0 here. The delay is a plain number in milliseconds, so 0 means start right away.
The report thread uses k_thread_create. Here you make the stack and the control block yourself, and you call the function when you want the thread to start. That is useful when the thread depends on something you set up first in main(), like a sensor that has to be checked.
There is one small trap. The start delay in k_thread_create is not a number. It is a k_timeout_t. You write K_NO_WAIT to start now, or something like K_MSEC(100) for a delay. In K_THREAD_DEFINE the same delay is plain milliseconds. Mixing these up is a common compile error.
k_thread_name_set gives the report thread a name. K_THREAD_DEFINE already names its thread after the id, so the blink thread shows up as blink_tid.
Stacks
Every thread needs its own stack. For a thread you create with k_thread_create, you make the stack with K_THREAD_STACK_DEFINE(report_stack, REPORT_STACK_SIZE). Do not use a plain char array. Some CPUs need the stack aligned in a special way, or need extra room for a guard area. The macro handles that for each architecture.
When you pass the stack to k_thread_create, pass its size with K_THREAD_STACK_SIZEOF(report_stack), not with sizeof. The macro gives the usable size.
How big should a stack be? 1024 bytes is what the official basic threads sample uses for threads that blink and call printk. That is a fair start for small threads like ours. The stack holds local variables, plus the call chain of everything the thread calls. A printk with a few arguments can use more than you would guess. Later in this post I show how to measure real use instead of guessing.
Priorities: cooperative and preemptive
In Zephyr a lower number means a higher priority. A thread at priority 4 beats a thread at priority 7.
Negative priorities are cooperative. With the default settings, these go from -16 to -1. A cooperative thread keeps the CPU until it sleeps, waits on something, or calls k_yield(). No other thread can take the CPU from it, even one with a higher priority. Interrupts can still run.
Priorities from 0 up are preemptive. With the default settings, these go from 0 to 14. A preemptive thread can lose the CPU at any time if a thread with a higher priority becomes ready.
main() runs at priority 0 by default. Our blink thread is at 5 and the report thread is at 7, so all three are preemptive. This also explains the order at boot. The blink thread is created during boot, but main() has a higher priority, so main() runs first. It starts the report thread, prints its line and returns. Only then do the blink and report threads get the CPU.
For your own app threads, start with preemptive priorities. Use a cooperative priority only when you have a clear reason, like a short piece of work that must not be cut in half by another thread.

What the scheduler does when threads sleep
The scheduler has one simple rule. It runs the highest priority thread that is ready. If two ready threads have the same priority, the one that has waited longest goes first.
k_msleep(500) takes the blink thread out of the ready list for 500 ms. The scheduler then looks for the next ready thread. Here that is the report thread, if it has something to print. When the report thread also goes to sleep, no app thread is ready. Then the scheduler runs the idle thread. The idle thread has the lowest priority of all, and its job is to wait for the next interrupt.
On our board that means the CPU spends almost all its time in the idle thread. The blink thread runs for a tiny moment every 500 ms. The report thread runs for a little longer every two seconds, because printk sends characters out of the UART. A timer interrupt wakes each thread when its sleep is over.
This is why k_msleep is so different from a busy delay. A sleeping thread costs nothing. Other threads get the CPU while it waits.
k_yield() is a softer step. It does not sleep. It puts the thread at the back of the line for its own priority, and lets any ready thread of the same or higher priority run first. If no such thread is ready, the thread just keeps going. A lower priority thread will never get the CPU because of k_yield().
Time slicing
Time slicing only matters when two preemptive threads have the same priority and both are ready for a long time.
Without slicing, the first one keeps the CPU until it sleeps or yields. The other one waits, even though its priority is the same. With CONFIG_TIMESLICE_SIZE=10, the kernel steps in after 10 ms and lets the other thread have a turn.
Time slicing never helps a lower priority thread. A thread at priority 7 still waits while a thread at priority 5 is ready. Slicing only shares the CPU among equals.
If you want to change the slice while the app runs, k_sched_time_slice_set(slice_ms, prio) does the same job as the two Kconfig options.
Build and flash
Activate the virtual environment, go to the app folder, then build and flash. In PowerShell:
cd $Env:HOMEPATH\zephyrproject
.\.venv\Scripts\Activate.ps1
cd app\threads_blink
west build -p always -b esp32s3_devkitc/esp32s3/procpu
west flash
west espressif monitor
On Linux or macOS:
source ~/zephyrproject/.venv/bin/activate
cd ~/zephyrproject/app/threads_blink
west build -p always -b esp32s3_devkitc/esp32s3/procpu
west flash
west espressif monitor
If west flash cannot find the board, add --esp-device COM5 on Windows or --esp-device /dev/ttyUSB0 on Linux, with your own port. The last post has more help for flash and port problems. To leave the monitor, type Ctrl+].
Read the output
After the Zephyr boot line you should see something like this:
main: priority 0, report thread started, main returns now
[0 ms] report: LED toggled 1 times
[2010 ms] report: LED toggled 4 times
[4020 ms] report: LED toggled 8 times
[6030 ms] report: LED toggled 12 times
[8040 ms] report: LED toggled 16 times
The exact numbers will be a bit different on your board. What matters is the pattern. The main line comes first, because main() has the highest priority. The LED changes state twice a second, so each report line shows about four more toggles than the one before. Two threads are running, and neither one waits for the other.
Notice the report times creep up a little each round. k_msleep(2000) sleeps for 2000 ms after the printk is done, and printing takes a little time. If you need a steady period, a k_timer is the better tool. That is a topic for another post.
A common mistake: a loop that never sleeps
Now break it on purpose. In main.c, set RUN_BUSY_DEMO to 1, then build and flash again. This adds a third thread at priority 4. It starts five seconds after boot and spins in k_busy_wait() forever. k_busy_wait() burns time without giving up the CPU, the same as a while loop that checks a flag.
For five seconds everything looks normal. Then you see busy: starting a loop that never sleeps, and the LED stops. The report lines stop too. The busy thread has priority 4, which is higher than both of ours, and it is always ready. So the scheduler always picks it. The other threads never crash. They are ready and waiting, but they never get a turn. This is called starvation.
Try a few changes and watch the board:
Set BUSY_PRIORITY to 5, the same as the blink thread. Thanks to the 10 ms time slice, the LED keeps blinking, and only the report thread starves. Now set CONFIG_TIMESLICE_SIZE=0 in prj.conf and build again. The LED stops again, because without a slice nothing makes the busy thread let go.
Keep BUSY_PRIORITY at 5 and slicing off, and add k_yield(); inside the busy loop. The LED comes back, because the yield lets the blink thread run. The report thread still starves, because k_yield() never helps a lower priority.
Set BUSY_PRIORITY to 10. Now everything works. The busy thread only gets the CPU when our two threads are asleep, which is most of the time. It takes over from the idle thread, so the board never rests, but nothing starves.
The real fix is to make long work wait properly. If a thread is polling for something, add a k_msleep() in the loop, or better, have it wait on a semaphore or a queue that an interrupt or another thread fills. If the work truly needs to run all the time, give it the lowest priority in your app, below the threads that must react quickly.
Another common mistake: a stack that is too small
A stack that is too small rarely gives a clean error by default. The thread writes past the end of its stack into other memory. You may get a crash with a register dump, or a variable in another thread that changes for no reason. Often it only shows up when a deeper call or a printk with more arguments runs.
Two Kconfig options help. To measure real stack use, add these lines to prj.conf while you test:
CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_USE_PRINTK=y
CONFIG_THREAD_ANALYZER_AUTO=y
CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=5
Every five seconds the monitor then shows each thread with its stack size and how much of it has been used, plus its share of the CPU. Here is part of the output from the QEMU emulator:
Thread analyze:
report : STACK: unused 572 usage 452 / 1024 ( 44 %); CPU: 0 %
blink_tid : STACK: unused 748 usage 276 / 1024 ( 26 %); CPU: 0 %
idle : STACK: unused 796 usage 228 / 1024 ( 22 %); CPU: 99 %
The report thread uses more stack than the blink thread, because of printk. The idle thread has 99 % of the CPU, which is what the section on sleeping threads said. main is not in the list, because its thread ended when main() returned. You will also see a thread_analyzer line, which is the analyzer itself.
Let the app run through all its normal paths, then read the numbers. Keep a safe margin above the highest use you see. Remove these lines when you are done, because the analyzer adds its own thread and stack.
While you develop, you can also add CONFIG_STACK_SENTINEL=y. Zephyr then writes a marker at the far end of each stack and checks it at every thread switch. If the marker is damaged, the thread is stopped with a fatal error. It catches many small overflows, but not all of them. A big overflow can crash the CPU before the check ever runs.
You can see that last case for yourself. Set REPORT_STACK_SIZE to 256 and build again. On the emulator, the app prints the first report line and then stops with a CPU exception. Even the fatal error message comes out garbled, because the overflow has already damaged memory. That is what a stack problem often looks like. When a crash makes no sense, check the stack sizes first.
A few more problems you may hit:
The build fails on k_thread_create with an error about the last argument. You passed 0 as the delay. Use K_NO_WAIT.
The report thread never prints, but the LED blinks. Check that main() actually calls k_thread_create. A thread made with K_THREAD_STACK_DEFINE alone does nothing until you create it.
The LED never blinks. Check that app.overlay is in the app folder, next to CMakeLists.txt, and that the build target is procpu.
Try it yourself
-
Change
BLINK_PERIOD_MSto 100. Each report line should now show about 20 more toggles. Only one thread changed. The report thread did not need to know. -
Wire a second LED on GPIO 5, add an
led1alias inapp.overlay, and give it its own thread that blinks at 300 ms. UseK_THREAD_DEFINEfor one LED thread andk_thread_createfor the other. -
Turn on the thread analyzer lines above and read the stack use for
blink_tidandreport. Lower the stack sizes to fit, with a margin, and check that the app still runs. -
Change
REPORT_PRIORITYto -1, which makes the report thread cooperative. The app still works, because the report thread sleeps. Look at the first lines in the monitor, though. The first report line now comes before themainline. Priority -1 is higher than the 0 thatmain()runs at, so the report thread takes the CPU the momentk_thread_createmakes it ready.
Where to go from here
You now have two threads that share the CPU, each with its own stack and priority. You have also seen what the scheduler does when threads sleep, and what happens when a thread never does. A good next step is to make threads talk to each other properly, with a semaphore or a message queue instead of a shared counter. The first Zephyr post gave a small taste of that.
If you want to work through this on a real board with labs, our Zephyr RTOS on ESP32-S3 course covers threads and the scheduler, then semaphores, mutexes and message queues, and later Wi-Fi and OTA.
Frequently asked questions
How do I create a thread in Zephyr on the ESP32-S3?
Use K_THREAD_DEFINE to create a thread at build time, or k_thread_create with a stack from K_THREAD_STACK_DEFINE to create it at run time. Both take an entry function with three void * arguments, a stack size, a priority, options and a start delay. They work the same on the ESP32-S3 as on any other Zephyr board.
How do thread priorities work in Zephyr?
A lower number means a higher priority. Negative priorities are cooperative, and a cooperative thread keeps the CPU until it sleeps or yields. Priorities from 0 up are preemptive, and a higher priority thread can take the CPU from them at any time. By default main() runs at priority 0.
What does the Zephyr scheduler do when all threads are sleeping?
It runs the idle thread, which has the lowest priority of all and waits for the next interrupt. When a sleep ends, a timer interrupt makes that thread ready again, and the scheduler switches to it if it has the highest priority among ready threads.
What is the difference between k_msleep and k_yield in Zephyr?
k_msleep takes the thread out of the ready list for a set time, so threads of any priority can run. k_yield does not sleep. It only lets ready threads of the same or higher priority run first, then the thread continues.
Why does my Zephyr thread never run?
Most often a higher priority thread never sleeps, so the scheduler never picks the lower one. A thread at the same priority can also starve if time slicing is off, which is the default behaviour in Zephyr 4.1 because CONFIG_TIMESLICE_SIZE is 0 there. Add a sleep or a blocking wait to the busy thread, or lower its priority.
How big should a Zephyr thread stack be?
1024 bytes is a common starting point for small threads that call printk, and it is what the official threads sample uses. Measure the real use with CONFIG_THREAD_ANALYZER, then keep a margin. Turn on CONFIG_STACK_SENTINEL while you develop to catch overflows early.