This post was first published on Jupius Learning, where you can read it free with diagrams and practice exercises.

Subscribe to our articles for regular updates.

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.

Read the rest on Jupius

That covers the app folder, the full main.c with two threads, and the two ways to create a thread. The second half of the post is where the scheduler comes in: how big a stack should be, cooperative and preemptive priorities, what the scheduler runs while threads sleep, time slicing, the west commands to build and flash, and a loop that never sleeps so you can watch a thread starve on the board. It ends with a few exercises and an FAQ.

Read the full post on Jupius Learning. It is free, with the scheduler diagram and the practice exercises.

If you want to go further on a real ESP32-S3 board, the Zephyr RTOS on ESP32-S3 course at Jupius Learning covers threads and the scheduler, then semaphores, mutexes and message queues.