</>EmbeddedInterview

What is the difference between a kernel thread and a user thread?

EasyLinux Kernel & Device Drivers

Short answer: A kernel thread runs entirely in kernel space, has no user address space (its mm is NULL; it borrows the previous task's page tables), and is created with kthread_run() or by subsystems (kworker, ksoftirqd, irq/NN-name, kswapd, rcu_*). A user thread belongs to a process, shares that process's address space and file descriptors, runs user code at EL0, and enters the kernel only through system calls, exceptions and interrupts. Both are task_structs scheduled by the same scheduler.

Creating a kernel thread in a driver

static int poll_fn(void *data)
{
    struct mydev *d = data;
    while (!kthread_should_stop()) {
        poll_hardware(d);
        msleep_interruptible(10);
    }
    return 0;
}

d->task = kthread_run(poll_fn, d, "mydev-poll");
if (IS_ERR(d->task)) return PTR_ERR(d->task);
/* in remove: */ kthread_stop(d->task);

Points

  • Kernel threads appear in ps in square brackets ([kworker/0:1H]).
  • Prefer workqueues or threaded IRQs over custom kthreads unless you need a dedicated, long-running loop or a specific RT priority (sched_set_fifo(task)).
  • In Linux, user threads are created with clone() sharing the address space (pthreads, 1:1 model): each user thread has its own kernel task_struct and kernel stack.
  • Kernel threads can be frozen during suspend (set_freezable(), try_to_freeze()).