Day68 - Kernel Thread Fundamentals¶
Objective¶
Learn the fundamentals of Linux kernel threads and understand how they differ from workqueues and threaded IRQ handlers.
Topics covered:
- Kernel thread lifecycle
kthread_run()kthread_should_stop()kthread_stop()- Wait queues
wait_event()wake_up()wait_event_timeout()- Event-driven thread design
- State machine integration
Lab 1 - Basic Kernel Thread¶
Goal¶
Create a simple kernel thread and verify:
- thread creation
- periodic execution
- graceful termination
Driver Structure¶
Thread Function¶
static int demo_kthread_fn(void *arg)
{
while (!kthread_should_stop()) {
pr_info("[TASK] alive\n");
msleep(1000);
}
return 0;
}
Module Init¶
Module Exit¶
Expected Result¶
Verification¶
Lab 2 - Wait Queue Integration¶
Goal¶
Replace polling with event-driven execution.
Driver Structure¶
struct kthread_demo_dev {
struct task_struct *thread;
wait_queue_head_t wq;
atomic_t manual_triggered;
};
Wait Queue Initialization¶
Thread Loop¶
Event Producer¶
Observation¶
The thread remains asleep until an event occurs.
This eliminates unnecessary periodic wakeups.
Lab 3 - wait_event_timeout()¶
Goal¶
Add timeout-driven behavior.
Thread Loop¶
ret = wait_event_timeout(
mydev->wq,
atomic_read(&mydev->manual_triggered) ||
kthread_should_stop(),
msecs_to_jiffies(5000));
Return Value¶
Observation¶
Unlike many Linux APIs, timeout returns zero.
Successful wakeup returns the remaining jiffies before timeout expiration.
Lab 4 - Simple State Machine¶
Goal¶
Use a kernel thread as a state machine execution engine.
States¶
State Flow¶
Thread Architecture¶
Observation¶
The kernel thread becomes an event loop.
The state machine contains business logic while the thread provides scheduling and execution context.
Threaded IRQ vs Workqueue vs Kernel Thread¶
| Feature | Threaded IRQ | Workqueue | Kernel Thread |
|---|---|---|---|
| Process Context | Yes | Yes | Yes |
| Sleep Allowed | Yes | Yes | Yes |
| Dedicated Thread | IRQ-specific | No | Yes |
| Long-lived State Machine | Limited | Moderate | Excellent |
| Event Loop Design | No | No | Yes |
| Background Service Pattern | No | Limited | Yes |
Key Takeaways¶
- Kernel threads are long-lived execution contexts.
- Wait queues provide efficient event-driven scheduling.
wait_event_timeout()supports timeout-based state transitions.- Kernel threads are well suited for protocol managers and state machines.
- Workqueues execute jobs, while kernel threads implement event loops.