Skip to content
systemcoding.dev
RTOS

Offload Work From ISRs With the Zephyr System Workqueue

Move slow work out of a Zephyr interrupt handler with k_work_submit and the system workqueue, with the work item rules, a GPIO example and sizing tips.

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

An interrupt handler has one job: acknowledge the hardware, capture what cannot wait, and get out. Anything slower, such as parsing a packet, writing to flash, formatting a log line or talking to another device over a bus, belongs in a thread. Zephyr provides a ready-made thread for that handoff, the system workqueue, and a small object, the work item, that describes what to run there. This post shows the pattern in Zephyr 4.2 with a GPIO interrupt, explains how work items are submitted and what state they move through, and lists the rules and limits of the system queue. It assumes you know what a thread and an ISR are, as covered in the guide to threads and synchronization.

The pattern in one picture

An interrupt fires. The handler runs on the interrupt stack with a strict budget. It stores the minimum, then calls k_work_submit(). That call appends the work item to the queue and wakes the system workqueue thread if it was idle. The handler returns. Later, when the scheduler picks the workqueue thread, the thread removes the item and calls its handler function, in a normal thread context where blocking calls are allowed. The reference is the workqueue documentation.

The system workqueue is a thread created by the kernel at boot. Its stack size is CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE and its priority CONFIG_SYSTEM_WORKQUEUE_PRIORITY. Both matter, and both can be wrong for your use, so check them in your build's .config.

A GPIO interrupt that submits work

This program reads a button with an interrupt and prints a message from a work handler. The ISR only records the time and submits:

src/main.cc
#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;

static int64_t press_time;
static struct k_work press_work;

static void press_handler(struct k_work *work)
{
	printk("button pressed at %lld ms (handled in a thread)\n", press_time);
	k_msleep(50);
}

static void button_isr(const struct device *dev, struct gpio_callback *cb,
		       uint32_t pins)
{
	press_time = k_uptime_get();
	k_work_submit(&press_work);
}

int main(void)
{
	if (!gpio_is_ready_dt(&btn)) {
		return 0;
	}
	k_work_init(&press_work, press_handler);

	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);

	printk("ready\n");
	return 0;
}
prj.confText
CONFIG_GPIO=y
CONFIG_PRINTK=y

A work item is a struct k_work, initialized with k_work_init(&item, handler) or defined statically with K_WORK_DEFINE(name, handler). The handler receives a pointer to the work item. After you press the button twice, the console reads:

Text
*** Booting Zephyr OS build v4.2.0 ***
ready
button pressed at 2314 ms (handled in a thread)
button pressed at 3470 ms (handled in a thread)

The times depend on when you press. Note the k_msleep(50) in the handler. That would be illegal in an ISR, and it is fine here because the handler runs in the workqueue thread. It also shows the cost: while it sleeps, no other item on the system queue runs.

The life of a work item

A work item is always in some combination of these states, and the API is built around them:

StateMeaning
IdleNot queued and not running
QueuedIn the queue, waiting for the thread
RunningThe handler is executing
CancelingA cancel is in progress

k_work_submit(&work) queues the item if it is idle. If it is already queued but not yet running, a second submit does nothing, and the handler runs once. If it is running, the submit queues it again, and the handler runs a second time after the first finishes. The return value tells you which case happened: 1 if newly queued, 0 if it was already queued, 2 if it was running and is now queued again, and a negative value on error.

This behavior matters for ISRs. If a button fires five times before the thread gets to run, the handler runs once, and your data reflects the latest state. A handler that must process every event needs a queue of events, not a work item per event. Pass data through a ring buffer, k_msgq or a FIFO, and let the handler drain it.

Passing context to the handler

The handler gets only a pointer to the work item. To reach your data, embed the work item in a structure and recover the structure with CONTAINER_OF:

c
struct button_event {
	struct k_work work;
	int pin;
	int64_t when;
};

static struct button_event ev;

static void button_work(struct k_work *work)
{
	struct button_event *e = CONTAINER_OF(work, struct button_event, work);

	printk("pin %d at %lld\n", e->pin, e->when);
}

/* setup */
k_work_init(&ev.work, button_work);

/* in the ISR */
ev.pin = 11;
ev.when = k_uptime_get();
k_work_submit(&ev.work);

This is the idiom throughout Zephyr. The work item's lifetime must cover the time it is queued, so make it static or part of a longer-lived object. Never put a work item on a thread's stack and return while it is queued.

Because the ISR writes ev and the handler reads it with no lock, a second interrupt during the handler would overwrite the fields mid-read. For a single event that is fine, and for several, use a queue.

Which queue runs the work

k_work_submit uses the system workqueue, k_sys_work_q. You can submit to another queue with k_work_submit_to_queue(&my_queue, &work), which the post on dedicated workqueues covers. The system queue is shared by drivers and subsystems, including parts of the networking and Bluetooth stacks, so what you run there can delay them. This is the central design rule: the system workqueue is a shared resource, so handlers on it must be short and must not block for long.

Three limits follow.

Ordering is first in, first out. Items run one after another in the order they were queued. A slow handler delays everything behind it.

One thread runs everything. The handlers never run in parallel on one queue. That makes them safe against each other, which is convenient for protecting shared state without a lock, and a handler that waits forever blocks the queue forever.

The queue's priority is fixed. By default it is a cooperative priority on some configurations. Check CONFIG_SYSTEM_WORKQUEUE_PRIORITY in .config. A handler that spins, at that priority, can starve application threads.

Sizing the system queue's stack

Handlers run on the workqueue thread's stack, so the stack must fit the deepest handler. The default, CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE, is around 1024 bytes on small builds and more with networking. Raise it if a handler uses printk with formatting, logging, a file system or a bus transfer:

prj.confText
CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=2048

Check usage with the thread analyzer, which lists the sysworkq thread with its stack high-water mark. If a handler is large, a dedicated queue with its own stack is better than enlarging the shared one for everyone.

Submitting from different contexts

k_work_submit is safe from any context: a thread, an ISR, a timer callback. It does not block. Other work API calls have rules:

CallFrom an ISR?Note
k_work_submitYesDoes not block
k_work_initYes, but do it once at startupInitializes the item
k_work_cancelYesReturns a status, does not wait
k_work_cancel_syncNoBlocks until the handler finishes
k_work_flushNoBlocks until the item has run

A common error is calling k_work_cancel_sync from an ISR, which asserts on debug builds. The next posts cover delayed work and cancellation.

Mistakes to avoid

Doing the real work in the ISR anyway. If you find a k_msleep or a bus transaction in an interrupt callback, move it to the handler.

Assuming each submit runs the handler once. Submits that arrive while the item is queued are merged.

Initializing the work item in the ISR for each event. k_work_init on an item that is queued corrupts the queue. Initialize once at startup.

A handler that runs forever. A while (1) in a work handler never returns, so the queue is dead. Handlers must return.

Forgetting stack and priority. Reading a hard fault after adding logging to a handler is usually a stack that is too small.

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.