Zephyr Semaphores and Mutexes: Syncing Threads on ESP32-S3
Use k_sem and k_mutex to sync Zephyr threads on the ESP32-S3. Signal a thread from a timer, protect shared data and see priority inheritance in QEMU.

In the last post we split the blink app into two threads. They shared one counter, and I used atomic_inc so the report thread never saw half an update. I also said that a semaphore or a mutex is the better tool once the shared thing is bigger than a counter. This post is about those two.
Threads that never talk to each other are easy. Real apps need them to cooperate. One thread has to wait until another has something for it. Two threads have to touch the same data without breaking it. A semaphore fixes the first problem. A mutex fixes the second.
We use two small apps. The first one wakes the LED thread from a timer with a semaphore. The second one needs no hardware. It runs short experiments with semaphores and mutexes and prints what each thread does, so you can follow along line by line.
What you need
You need the same setup as the last two posts. Your Zephyr workspace and west should already work. The first app post has the install steps and the LED wiring on GPIO 4. The build target is still esp32s3_devkitc/esp32s3/procpu. If words like thread or scheduler are new, the first Zephyr post explains them.
Zephyr 4.1 is the version the earlier posts followed. Both apps build for that target on Zephyr 4.1 and on Zephyr 4.5 with no warnings. The APIs in this post are the same in both versions.
Please read this part before you look at any output. Every output block below comes from the QEMU Xtensa emulator, running Zephyr 4.5. None of it comes from an ESP32-S3 board. These two apps were not run on a board for this post. The emulator has no pin GPIO 4, so for the LED app I pointed led0 at the emulated GPIO controller that Zephyr ships. The C code is the same code you will build for the board. The millisecond values will be different on real hardware, so use the output to see the pattern, not the numbers.
Two jobs for two tools
A semaphore is for telling a thread that something happened. A timer fired, or a byte arrived. The thread waits until it gets the signal, and then it does the work.
A mutex is for sharing. Two threads want to change the same variable, or use the same bus. A mutex lets one at a time in. The name comes from "mutual exclusion".
They look alike, because both can make a thread wait. The difference is who is in charge. A semaphore has no owner. Any thread, or an interrupt, can give it, and any thread can take it. A mutex has an owner. The thread that locks it must be the thread that unlocks it. That owner is what makes priority inheritance possible, and we will get to that.
How a semaphore works
A semaphore is a counter with one rule. k_sem_give adds one to the count. k_sem_take takes one away. If the count is zero, k_sem_take waits until someone gives. The count can never go above a limit that you pick.
You can create one at build time with K_SEM_DEFINE:
K_SEM_DEFINE(tick_sem, 0, 1);
The arguments are the name, the starting count and the limit. This one starts at 0, so the first k_sem_take waits. The limit is 1, so it can hold at most one signal. A semaphore with a limit of 1 is often called a binary semaphore. With a bigger limit it is a counting semaphore, which fits a pool of identical things, like a pool of free buffers. The limit must be more than 0, and the starting count cannot be above it. Otherwise the build fails. If you need to set one up at run time, use k_sem_init.
k_sem_take takes a timeout. K_FOREVER waits as long as it needs. K_NO_WAIT never waits. K_MSEC(1200) waits up to 1200 ms. It returns 0 when it got the semaphore. It returns -EBUSY when you passed K_NO_WAIT and the count was zero. It returns -EAGAIN when the time ran out.
One rule matters a lot on a microcontroller. k_sem_give is safe to call from an interrupt handler. k_sem_take is only safe there with K_NO_WAIT, because an interrupt must never wait.
Wake the LED thread from a timer
Here is the first app. A timer fires every 500 ms. Its handler gives a semaphore. The LED thread takes the semaphore and toggles the pin. Make a folder next to the others, for example zephyrproject/app/sem_blink, with the same layout as before:
sem_blink/
├── CMakeLists.txt
├── app.overlay
├── prj.conf
└── src
└── main.c
CMakeLists.txt has a new project name:
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr)
project(sem_blink)
target_sources(app PRIVATE src/main.c)
Copy app.overlay from the earlier apps without any change. It still gives us led0 on GPIO 4:
/ {
aliases {
led0 = &ext_led;
};
leds {
compatible = "gpio-leds";
ext_led: led_0 {
gpios = <&gpio0 4 GPIO_ACTIVE_HIGH>;
};
};
};
prj.conf needs only one line this time:
CONFIG_GPIO=y
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 TICK_PERIOD_MS 500
#define MAX_TOGGLES 6
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
/* Starts at 0 (nothing to take yet) and holds at most 1 */
K_SEM_DEFINE(tick_sem, 0, 1);
/* Runs in the timer interrupt context, so it must not block */
static void tick_handler(struct k_timer *timer)
{
ARG_UNUSED(timer);
k_sem_give(&tick_sem);
}
K_TIMER_DEFINE(tick_timer, tick_handler, NULL);
static void led_thread(void *p1, void *p2, void *p3)
{
int toggles = 0;
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
if (!gpio_is_ready_dt(&led)) {
printk("led: LED GPIO is not ready\n");
return;
}
if (gpio_pin_configure_dt(&led, GPIO_OUTPUT_INACTIVE) < 0) {
printk("led: failed to configure the LED pin\n");
return;
}
while (1) {
int ret = k_sem_take(&tick_sem, K_MSEC(1200));
if (ret == -EAGAIN) {
printk("[%u ms] led: no tick for 1200 ms, thread ends\n",
k_uptime_get_32());
return;
}
gpio_pin_toggle_dt(&led);
toggles++;
printk("[%u ms] led: toggle %d\n", k_uptime_get_32(), toggles);
if (toggles == MAX_TOGGLES) {
k_timer_stop(&tick_timer);
printk("[%u ms] led: timer stopped\n", k_uptime_get_32());
}
}
}
K_THREAD_DEFINE(led_tid, 1024, led_thread,
NULL, NULL, NULL, 5, 0, 0);
int main(void)
{
k_timer_start(&tick_timer, K_MSEC(TICK_PERIOD_MS), K_MSEC(TICK_PERIOD_MS));
printk("main: timer started, main returns now\n");
return 0;
}
Read it from the top. K_SEM_DEFINE makes the semaphore with a count of 0 and a limit of 1. K_TIMER_DEFINE makes a timer that calls tick_handler each time it expires. That handler runs in interrupt context, so it does one small thing and returns. It gives the semaphore. The real work, toggling the pin and printing, happens in the thread. This is a pattern you will use again and again: keep the interrupt short and hand the job to a thread.
main() only starts the timer and returns. The LED thread was created with K_THREAD_DEFINE, the same way as the blink thread in the last post.
Notice that the limit is 1. If the LED thread were slow and two ticks went by, the semaphore would still hold only one signal. That is what you want for "something happened". It is not a queue of events. If you must not lose any, you need a message queue, which is a topic for another post.
After six toggles the thread stops the timer. Then k_sem_take waits with a 1200 ms timeout, nothing arrives, and it returns -EAGAIN. The thread prints a line and returns, which ends it. That shows the timeout path without any extra code.
Build and flash the same way as before. On Linux or macOS:
source ~/zephyrproject/.venv/bin/activate
cd ~/zephyrproject/app/sem_blink
west build -p always -b esp32s3_devkitc/esp32s3/procpu
west flash
west espressif monitor
On Windows, use the PowerShell steps from the last post. This is what the QEMU run printed after the Zephyr boot line:
main: timer started, main returns now
[510 ms] led: toggle 1
[1010 ms] led: toggle 2
[1510 ms] led: toggle 3
[2010 ms] led: toggle 4
[2510 ms] led: toggle 5
[3010 ms] led: toggle 6
[3010 ms] led: timer stopped
[4220 ms] led: no tick for 1200 ms, thread ends
The LED thread wakes every 500 ms and does nothing in between. That is the same idea as k_msleep, except that the thread wakes because of an event and not because of a fixed delay. After the sixth toggle the timer stops. 1200 ms later the take times out and the thread ends.
A lab app with no hardware
For the rest of the post we use an app that needs no pin and no LED. It runs on any Zephyr board and on the emulator. Create zephyrproject/app/mutex_lab with the same layout, but without app.overlay. CMakeLists.txt is the same as before, with project(mutex_lab) instead. prj.conf has one line:
CONFIG_THREAD_NAME=y
Put this in src/main.c. It is long, but each of the three parts is short, and we go through them one at a time below.
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#define STACK_SIZE 1024
/* ---------- Part 1: a counting semaphore ---------- */
/* Two slots, both free at the start */
K_SEM_DEFINE(slots, 2, 2);
static void counting_demo(void)
{
for (int i = 1; i <= 3; i++) {
int ret = k_sem_take(&slots, K_NO_WAIT);
printk("take %d: ret %d, count now %u\n", i, ret, k_sem_count_get(&slots));
}
k_sem_give(&slots);
k_sem_give(&slots);
k_sem_give(&slots);
printk("after three gives: count %u (limit is 2)\n", k_sem_count_get(&slots));
}
/* ---------- Part 2: a shared counter, with and without a mutex ---------- */
#define ROUNDS 1000
K_MUTEX_DEFINE(shared_lock);
static int shared_counter;
static bool use_lock;
static K_THREAD_STACK_DEFINE(stack_a, STACK_SIZE);
static K_THREAD_STACK_DEFINE(stack_b, STACK_SIZE);
static K_THREAD_STACK_DEFINE(stack_c, STACK_SIZE);
static struct k_thread thread_a, thread_b, thread_c;
static void counter_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
for (int i = 0; i < ROUNDS; i++) {
if (use_lock) {
k_mutex_lock(&shared_lock, K_FOREVER);
}
int copy = shared_counter;
k_yield(); /* force a thread switch between the read and the write */
shared_counter = copy + 1;
if (use_lock) {
k_mutex_unlock(&shared_lock);
}
}
}
static void race_demo(bool lock)
{
use_lock = lock;
shared_counter = 0;
k_thread_create(&thread_a, stack_a, K_THREAD_STACK_SIZEOF(stack_a),
counter_thread, NULL, NULL, NULL, 5, 0, K_NO_WAIT);
k_thread_create(&thread_b, stack_b, K_THREAD_STACK_SIZEOF(stack_b),
counter_thread, NULL, NULL, NULL, 5, 0, K_NO_WAIT);
k_thread_join(&thread_a, K_FOREVER);
k_thread_join(&thread_b, K_FOREVER);
printk("%s: expected %d, got %d\n", lock ? "with mutex " : "without mutex",
2 * ROUNDS, shared_counter);
}
/* ---------- Part 3: priority inheritance ---------- */
#define LOW_PRIO 10
#define MID_PRIO 7
#define HIGH_PRIO 3
K_MUTEX_DEFINE(res_mutex);
K_SEM_DEFINE(res_sem, 1, 1); /* a binary semaphore guarding the same kind of resource */
static bool inv_use_mutex;
static void res_take(void)
{
if (inv_use_mutex) {
k_mutex_lock(&res_mutex, K_FOREVER);
} else {
k_sem_take(&res_sem, K_FOREVER);
}
}
static void res_give(void)
{
if (inv_use_mutex) {
k_mutex_unlock(&res_mutex);
} else {
k_sem_give(&res_sem);
}
}
static void low_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
res_take();
printk("[%3u ms] low : got the resource, priority %d\n",
k_uptime_get_32(), k_thread_priority_get(k_current_get()));
k_busy_wait(100 * USEC_PER_MSEC); /* 100 ms of work while holding it */
printk("[%3u ms] low : giving it back, priority %d\n",
k_uptime_get_32(), k_thread_priority_get(k_current_get()));
res_give();
printk("[%3u ms] low : done, priority %d\n",
k_uptime_get_32(), k_thread_priority_get(k_current_get()));
}
static void mid_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
printk("[%3u ms] mid : starts 200 ms of work that needs no resource\n",
k_uptime_get_32());
k_busy_wait(200 * USEC_PER_MSEC);
printk("[%3u ms] mid : done\n", k_uptime_get_32());
}
static void high_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
printk("[%3u ms] high: wants the resource\n", k_uptime_get_32());
res_take();
printk("[%3u ms] high: got the resource\n", k_uptime_get_32());
res_give();
}
static void inversion_demo(bool use_mutex)
{
inv_use_mutex = use_mutex;
printk("--- %s ---\n", use_mutex ? "k_mutex" : "k_sem used as a lock");
k_thread_create(&thread_a, stack_a, K_THREAD_STACK_SIZEOF(stack_a),
low_thread, NULL, NULL, NULL, LOW_PRIO, 0, K_NO_WAIT);
k_thread_create(&thread_b, stack_b, K_THREAD_STACK_SIZEOF(stack_b),
high_thread, NULL, NULL, NULL, HIGH_PRIO, 0, K_MSEC(20));
k_thread_create(&thread_c, stack_c, K_THREAD_STACK_SIZEOF(stack_c),
mid_thread, NULL, NULL, NULL, MID_PRIO, 0, K_MSEC(40));
k_thread_join(&thread_a, K_FOREVER);
k_thread_join(&thread_b, K_FOREVER);
k_thread_join(&thread_c, K_FOREVER);
}
int main(void)
{
printk("== counting semaphore ==\n");
counting_demo();
printk("== shared counter ==\n");
race_demo(false);
race_demo(true);
printk("== priority inversion ==\n");
k_sem_init(&res_sem, 1, 1);
inversion_demo(false);
inversion_demo(true);
return 0;
}
To run it on the emulator, build for qemu_xtensa/dc233c, then run west build -t run. The Xtensa QEMU comes with the Zephyr SDK. To run it on the board, build for the ESP32-S3 target as usual and read the output in the monitor. The program prints everything once and then sits idle.
Part 1: a counting semaphore
K_SEM_DEFINE(slots, 2, 2) makes a semaphore with two free slots. The first part of main() takes three times with K_NO_WAIT, then gives three times. This is the first block of output:
take 1: ret 0, count now 1
take 2: ret 0, count now 0
take 3: ret -16, count now 0
after three gives: count 2 (limit is 2)
The first two takes work and drop the count to 0. The third one fails at once with -16, which is -EBUSY, and the count stays at 0. Then we give three times, but the count stops at 2. The limit does its job. Extra gives are not stored.
Part 2: sharing data with a mutex
Now two threads, both at priority 5, each add 1 to shared_counter 1000 times. The right answer is 2000.
Each round reads the counter into copy, then writes copy + 1 back. That is three steps in the machine, not one. If a thread switch happens between the read and the write, the other thread can read the old value, and one update is lost. Real code hits this only now and then, which makes it a bad bug to chase. In the lab I call k_yield() between the read and the write. That forces the bad timing every time, so the bug shows up on every run.
race_demo(false) runs the threads with no lock. race_demo(true) locks shared_lock around the read and the write. The lock is made with K_MUTEX_DEFINE(shared_lock), and the thread uses k_mutex_lock and k_mutex_unlock. Here is the second block of output:
without mutex: expected 2000, got 1000
with mutex : expected 2000, got 2000
Without the mutex, half of the updates are gone. Both threads read the same value, both write that value plus one, and one of the two increments disappears. With the mutex the answer is exactly 2000. The second thread waits at k_mutex_lock until the first one has finished its read and write.
The main program waits for the two threads with k_thread_join. That call blocks until the thread has ended, so we can read the final count safely.
Some rules for k_mutex:
k_mutex_lock takes a timeout like k_sem_take. It returns 0 on success, -EBUSY if you passed K_NO_WAIT and someone else holds it, and -EAGAIN if the time ran out.
Only the owner may unlock. If another thread calls k_mutex_unlock, it gets -EPERM. If the mutex is not locked at all, you get -EINVAL.
A thread that already owns the mutex can lock it again. Zephyr counts the locks, and the mutex is free only after the same number of unlocks. That helps when one function that locks calls another function that also locks.
A mutex cannot be used in an interrupt handler. If you need to protect data that an interrupt also touches, a mutex is the wrong tool.
Keep the locked part short. In the lab the k_yield() sits inside the lock only to prove a point. In real code, do not sleep or wait for something slow while you hold a lock, because every other thread that needs it has to wait too.
Part 3: priority inversion and priority inheritance
This one is a classic problem, and it is the main reason a mutex is not just a semaphore with an owner.
Remember that in Zephyr a lower number means a higher priority. We have three threads. low runs at priority 10 and mid at 7. high is the most important one, at priority 3. The story goes like this.
low takes the lock and starts 100 ms of work. While it is working, high wakes up and wants the same lock. It has to wait, because low holds it. That is fine so far. Then mid wakes up. It does not need the lock, and its priority is higher than low. So the scheduler runs mid, and low cannot finish its work and release the lock. high is now stuck behind mid, a thread that has a lower priority than it. This is priority inversion.
The lab runs the story twice. The first time the lock is a binary semaphore, made with K_SEM_DEFINE(res_sem, 1, 1). The second time it is a k_mutex. The res_take and res_give helpers pick one or the other. The high thread starts 20 ms after low, and mid starts 40 ms after low. Here is the third block of output:
--- k_sem used as a lock ---
[170 ms] low : got the resource, priority 10
[200 ms] high: wants the resource
[220 ms] mid : starts 200 ms of work that needs no resource
[420 ms] mid : done
[420 ms] low : giving it back, priority 10
[420 ms] high: got the resource
[420 ms] low : done, priority 10
--- k_mutex ---
[420 ms] low : got the resource, priority 10
[450 ms] high: wants the resource
[520 ms] low : giving it back, priority 3
[520 ms] high: got the resource
[520 ms] mid : starts 200 ms of work that needs no resource
[720 ms] mid : done
[720 ms] low : done, priority 10
Look at the semaphore run first. low gets the resource. high asks for it and waits. mid starts its 200 ms of work, and it finishes before anything else happens. Only then does low get the CPU back and give the resource, and high gets it at 420 ms. The low thread stayed at priority 10 the whole time.
Now the mutex run. low gets the lock at priority 10. When high starts to wait on the same mutex, the kernel raises the priority of low to 3, which is the priority of the waiter. This is called priority inheritance. You can see it in the line where low gives the lock back: its priority is 3. Because of that, mid could not take the CPU from low. low finished its 100 ms, unlocked, and high got the lock at 520 ms, which is 100 ms after low took it. mid only started after that. When low unlocked, the kernel put its priority back to 10, and the last line shows it.
A semaphore cannot do this. It has no owner, so the kernel does not know which thread to speed up. That is why a lock that guards shared data should be a mutex, and why a semaphore is the right choice for signals.
The times in the output are a little off from the delays in the code, for example high wakes up 30 ms after low and not 20. That is the emulator and the tick. Look at the order of the lines and not at the exact numbers.
Inheritance helps, but it does not remove the cost. high still waited for the whole 100 ms that low held the lock. The best fix is still to keep the locked part short.
Common mistakes
A thread waits forever and never wakes up. Nobody gives the semaphore. Check that every path that should signal really calls k_sem_give, including the error paths. When you are not sure, use a timeout instead of K_FOREVER while you debug, and print the return value.
A mutex is unlocked by the wrong thread, and k_mutex_unlock returns -EPERM. The thread that locked it has to unlock it. If you need one thread to signal another, use a semaphore.
A mutex is used in an interrupt handler. That is not allowed. Use k_sem_give in the handler and do the locking in a thread.
A k_sem_take with a long timeout is called in an interrupt handler. Use K_NO_WAIT there, or move the wait to a thread.
Two threads each hold one lock and wait for the other one. Both wait forever. This is a deadlock. The usual cure is to always take locks in the same order.
The build fails on K_SEM_DEFINE with a message about the limit. The limit is 0, or the starting count is bigger than the limit.
The LED app builds, but the pin does nothing. Check that app.overlay is in the app folder next to CMakeLists.txt, and that the build target is procpu.
Try it yourself
-
In
sem_blink, changeTICK_PERIOD_MSto 250. The toggles should come twice as fast. The semaphore code does not change. -
In
sem_blink, change the timeout ink_sem_takefrom 1200 to 400. What happens, and why? Then change it to 600 and compare. -
In
mutex_lab, changeK_SEM_DEFINE(slots, 2, 2)toK_SEM_DEFINE(slots, 4, 4)and take four times. Print the return value of each take and read the count. -
In
mutex_lab, changeMID_PRIOto 12. Nowmidhas a lower priority thanlow, so it cannot get in the way. The semaphore run and the mutex run should both give the resource tohighright afterlowhas done its 100 ms of work.
Where to go from here
You now have both tools. A semaphore is for signals and for counting free things. A mutex is for protecting data, and it keeps a low priority owner from holding up a high priority thread. A good next step is the message queue, k_msgq, which passes whole messages between threads and can hold more than one.
If you want to practice this on a real board with labs, our Zephyr RTOS on ESP32-S3 course covers semaphores, mutexes and message queues after threads and the scheduler.
Frequently asked questions
What is the difference between a semaphore and a mutex in Zephyr?
A semaphore is a counter that any thread or interrupt can give, and any thread can take. It is for signals and for counting resources. A mutex has an owner, and only that thread can unlock it. It is for protecting shared data, and it supports priority inheritance.
How do I create a semaphore in Zephyr?
Use K_SEM_DEFINE(name, initial_count, count_limit) to create it at build time, or call k_sem_init on a struct k_sem at run time. Then use k_sem_give and k_sem_take. The limit must be more than 0, and the starting count cannot be above it.
Can I use a Zephyr semaphore or mutex inside an interrupt handler?
You can call k_sem_give from an interrupt handler. You can call k_sem_take there only with K_NO_WAIT. A mutex cannot be used in an interrupt handler at all, so give a semaphore from the handler and lock in a thread.
Does Zephyr have priority inheritance?
Yes, for k_mutex. When a higher priority thread waits for a mutex, the kernel raises the priority of the owner to match, then puts it back when the owner unlocks. A semaphore does not do this, because it has no owner.
What does k_sem_take return when it times out?
It returns -EAGAIN. If you called it with K_NO_WAIT and the count was zero, it returns -EBUSY instead. It returns 0 when it got the semaphore. k_mutex_lock uses the same codes.
Can a Zephyr thread lock the same mutex twice?
Yes. A k_mutex is recursive. The owner can lock it again, and the kernel counts the locks. The mutex becomes free only after the owner has unlocked it as many times as it locked it.
Do I need a mutex if I only have one core?
Often yes. Even with one core, the scheduler can switch threads in the middle of a read and write. The lab runs on a single emulated core and still loses updates. Use a mutex, or an atomic type for a single counter, for any data that more than one thread changes.