kthread¶
Purpose¶
Kernel threads provide long-lived execution contexts inside the Linux kernel.
Unlike workqueues, which execute individual deferred jobs and return, kernel threads continuously run until explicitly stopped.
Kernel threads are commonly used for:
- Protocol state machines
- Connection managers
- Background services
- Event-driven processing
- Long-lived driver tasks
Header¶
Key APIs¶
kthread_create()¶
Create a kernel thread without starting execution.
Prototype:
struct task_struct *kthread_create(
int (*threadfn)(void *data),
void *data,
const char namefmt[],
...);
Behavior:
- Allocate and initialize a kernel thread
- Thread is created in a stopped state
- Caller must invoke
wake_up_process()to start execution
Example:
wake_up_process()¶
Wake and schedule a sleeping task.
Prototype:
Typical usage:
kthread_run()¶
Create and start a kernel thread.
Prototype:
struct task_struct *kthread_run(
int (*threadfn)(void *data),
void *data,
const char namefmt[],
...);
Parameters:
| Parameter | Description |
|---|---|
threadfn |
Thread entry function |
data |
Private context pointer |
namefmt |
Thread name |
Return:
| Value | Meaning |
|---|---|
| Valid pointer | Thread created successfully |
ERR_PTR() |
Failure |
Example:
kthread_should_stop()¶
Check whether thread termination has been requested.
Prototype:
Typical usage:
kthread_stop()¶
Request thread termination and wait for thread exit.
Prototype:
Example:
Behavior:
- Set stop flag
- Wake sleeping thread
- Wait for thread exit
Thread Lifecycle¶
kthread_create()
↓
CREATED
↓
wake_up_process()
↓
RUNNING
↓
kthread_stop()
↓
STOP_REQUESTED
↓
thread exits
↓
EXITED
kthread_stop() does not forcibly terminate a thread.
The thread must periodically check:
and exit cooperatively.
Typical Thread Structure¶
static int demo_thread_fn(void *arg)
{
while (!kthread_should_stop()) {
wait_event(...);
process_event();
}
return 0;
}
Event-Driven Pattern¶
Kernel threads are commonly combined with wait queues.
Consumer:
Producer:
Typical architecture:
Common Pitfalls¶
Forgetting kthread_should_stop()¶
Incorrect:
The thread can never terminate cleanly.
Polling Instead of Waiting¶
Incorrect:
Prefer:
to avoid unnecessary wakeups.
Blocking for Long Periods¶
Long blocking operations can delay processing of new events.
Consider:
- wait queues
- event queues
- timeout-driven state machines
instead of long sleeps.
Related APIs¶
wait_event()wait_event_timeout()wake_up()workqueuedevm_request_threaded_irq()
Related Topics¶
- Kernel Thread Fundamentals
- Workqueue and Deferred Execution
- Completion Synchronization
- Wait Queue Internals