The Linux kernel spawns threads which handle background operation. These kernel threads have a PID and also contain a task structure similar to a process. However, the kernel thread does not have a specific address space where they are mapped to. The kernel threads run exclusively in kernel space and take care of asynchronous events or handle background operations.
All kernel threads are spawned from kthreadd which has a PID of 2 and is spawned during kernel init. The below “ps -ef” output shows the kthreadd kernel thread.
The kernel threads are constantly running threads. They can be created and stopped via the below kernel thread APIs. There are other helper functions and per cpu functionsand also a bind function (kthread_bind – to bind thread to a specific CPU). For a more detailed list – jump into /linux/kthread.h and also refer kthread.c.
Kernel Thread API | Description |
kthread_create | is a MACRO that creates a kernel thread. The thread is created in a stopped state and a “wake_up_process” API call on the thread is required to get the thread running |
kthread_run | The API combines “kthread_create” and “wake_up_process” API call to create and get the thread in running state. This API basically performs “create thread and run” |
kthread_stop | stop a thread created by kthread_create(). Sets kthread_should_stop() for @k to return true, wakes it, and waits for it to exit. |
In the next article, we will look at a small kernel module creating a kernel thread
Pingback: Creating a dedicated workqueue | Hitch Hiker's Guide to Learning