What is Linux Kernel Threads Tutorial-Linux Device Driver Training in Hyderabad

Linux Kernel Threads Tutorial
Free Linux Kernel Development Course • Kernel 6.x • kthread_run, kthread_stop, kthread_should_stop
100% Free
Kernel 6.x API
Real Driver Pattern

Welcome to this Linux kernel threads tutorial, the third lecture in EmbeddedPathashala’s free Linux kernel development course. Kernel timers, covered in the previous lecture, are perfect for short callbacks — but what if your driver needs a genuine background loop, one that can block, sleep, and keep running for the entire lifetime of the module? That is exactly the job of a Linux kernel thread, and this Linux kernel threads tutorial shows the modern kthread API used to create one safely.

What You Will Learn

  • What a kernel thread is and how it differs from a timer callback or a workqueue item
  • How to create and start a kernel thread with kthread_run()
  • How to stop a kernel thread cleanly using kthread_stop() and kthread_should_stop()
  • A complete, original polling-loop example

Prerequisites

This Linux kernel threads tutorial builds on the previous two lectures in this free Linux kernel development course — delay functions and kernel timers. Make sure you understand process versus atomic context before continuing.

Why Use a Kernel Thread At All

A kernel thread is a task that lives entirely inside the kernel, has its own stack, and is scheduled by the same scheduler as any user-space process — except it never returns to user space. It is the right tool when you need a background loop that can genuinely sleep between iterations, unlike a timer callback which must never block.

MechanismCan it sleep?Best for
Timer callbackNoShort, precise, periodic actions
Kernel threadYesLong-running background loops
Workqueue itemYesDeferred, event-driven, sleepable work

The Modern kthread API

Kernel Thread Lifecycle
kthread_run(fn, data, “name”) — create AND start the thread | v thread runs fn() in a loop, checking kthread_should_stop() each iteration | v module_exit calls kthread_stop(task) | v should_stop flag is set + thread is woken | v fn() notices the flag, breaks its loop, returns | v kthread_stop() returns fn()’s exit value
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/sched.h>

static struct task_struct *ep_thread;

static int ep_worker_fn(void *data)
{
    unsigned int count = 0;

    while (!kthread_should_stop()) {
        pr_info("ep_worker: still alive, tick %u\n", count++);

        /* schedule_timeout_interruptible lets the thread sleep
         * while still waking up promptly if kthread_stop() fires */
        set_current_state(TASK_INTERRUPTIBLE);
        schedule_timeout(msecs_to_jiffies(1000));
    }

    pr_info("ep_worker: stopping cleanly\n");
    return 0;
}

static int __init ep_kthread_init(void)
{
    ep_thread = kthread_run(ep_worker_fn, NULL, "ep_worker");
    if (IS_ERR(ep_thread))
        return PTR_ERR(ep_thread);

    pr_info("ep_kthread: module loaded\n");
    return 0;
}

static void __exit ep_kthread_exit(void)
{
    kthread_stop(ep_thread);
    pr_info("ep_kthread: module unloaded\n");
}

module_init(ep_kthread_init);
module_exit(ep_kthread_exit);
MODULE_LICENSE("GPL");

Why kthread_should_stop() Must Be Checked Every Loop

kthread_stop() does not forcibly kill the thread. It sets an internal flag and wakes the thread, then waits for it to return on its own. Your loop must actively check kthread_should_stop() after every wakeup, otherwise kthread_stop() will hang forever waiting for a thread that never checks the flag.

Common Mistakes

  • Using msleep() in a loop that ignores kthread_should_stop(), which delays shutdown by up to the full sleep interval or worse.
  • Calling kthread_stop() before the thread has actually started running, which is safe by design but easy to reason about incorrectly.
  • Forgetting to check IS_ERR() on the return value of kthread_run().
  • Spawning a new kernel thread for every minor background task instead of reusing a workqueue, which wastes memory on unnecessary kernel stacks.

Best Practices

  • Always check kthread_should_stop() right after waking from sleep, before doing any work.
  • Prefer a workqueue over a dedicated kernel thread unless you truly need a persistent, always-running loop.
  • Give threads a descriptive name — it shows up directly in ps and makes debugging much easier.

Performance Considerations

Each kernel thread carries its own kernel stack (typically several kilobytes) and adds one more entity for the scheduler to track. For infrequent or event-driven work, a workqueue is usually lighter-weight than a dedicated kernel thread that spends most of its life asleep.

Key Takeaways

  • Kernel threads are full scheduled tasks that can sleep, unlike timer callbacks.
  • kthread_run() both creates and starts a thread in one call.
  • Cooperative shutdown via kthread_should_stop() is mandatory, not optional.
  • Reach for a workqueue instead when the work is occasional rather than continuous.

Conclusion

This Linux kernel threads tutorial covered the complete lifecycle of a kthread-based background loop, from creation to cooperative shutdown. In the final lecture of this mini-series inside our free Linux kernel development course, we’ll cover workqueues — the preferred mechanism for deferred, sleepable work that doesn’t need a dedicated always-on thread.

Frequently Asked Questions

Q1. What is the difference between a kernel thread and a workqueue?

A kernel thread is a persistent background loop you manage yourself; a workqueue schedules discrete units of sleepable work onto a shared pool of worker threads managed by the kernel.

Q2. Why does my kthread_stop() call hang?

Most commonly because the thread’s loop never checks kthread_should_stop(), so it never notices the stop request and returns.

Q3. Can a kernel thread call msleep() or usleep_range()?

Yes, kernel threads run in normal process context, so all the blocking delay functions from earlier in this free Linux kernel development course are safe to use there.

Q4. What does kthread_run() return on failure?

It returns an error pointer, which you must check with IS_ERR() and convert with PTR_ERR() before treating it as a valid task_struct.

Q5. Is a dedicated kernel thread always the right choice?

No — for occasional or event-triggered work, a workqueue is usually more efficient than keeping a dedicated thread alive for the whole module lifetime.

Q6. Is this Linux kernel threads tutorial free?

Yes, it’s part of EmbeddedPathashala’s free Linux kernel development course, along with a free Linux device drivers course and a free embedded systems course.

linux kernel threads tutorial free linux kernel development course free linux device drivers course kthread_run kthread_stop
Continue This Free Linux Kernel Development Course

Next up: Linux Kernel Workqueues — the preferred way to defer sleepable work.

Next Lecture →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *