Skip to content

Linux 内核 kthread worker 机制详解

Linux 内核 kthread worker 机制详解(原理 + 接口使用 + 源码实现)

Section titled “Linux 内核 kthread worker 机制详解(原理 + 接口使用 + 源码实现)”

kthread worker 是 Linux 内核提供的一种异步任务执行机制,本质上是:

  • 一个专属内核线程(kthread)
  • 一个待执行 work 队列

它兼具 workqueue 的易用性,以及 kthread 的可控性。


相比 system_wq 共享线程池,kthread worker 具备:

  • 独占线程,减少竞争
  • 可绑定 CPU
  • 可设置优先级
  • 更稳定的 IO 时延
  • 更容易定位问题

适合 NVMe、块层、网络驱动等高性能路径。


头文件:include/linux/kthread.h

struct kthread_worker {
spinlock_t lock;
struct list_head work_list;
struct task_struct *task;
struct kthread_work *current_work;
};
struct kthread_work {
struct list_head node;
kthread_work_func_t func;
struct kthread_worker *worker;
};

worker = kthread_create_worker(0, "demo_worker");
kthread_init_work(&work, handler);
kthread_queue_work(worker, &work);
kthread_flush_work(&work);
kthread_cancel_work_sync(&work);
kthread_destroy_worker(worker);

#include <linux/module.h>
#include <linux/kthread.h>
static struct kthread_worker *worker;
static struct kthread_work mywork;
static void my_fn(struct kthread_work *work)
{
pr_info("hello worker\n");
}
static int __init demo_init(void)
{
worker = kthread_create_worker(0, "demo");
kthread_init_work(&mywork, my_fn);
kthread_queue_work(worker, &mywork);
return 0;
}
static void __exit demo_exit(void)
{
kthread_flush_work(&mywork);
kthread_destroy_worker(worker);
}

源码位置:kernel/kthread.c

  • 加锁保护队列
  • work 挂入 worker->work_list
  • wake_up_process(worker->task)

线程主循环:

while (!kthread_should_stop()) {
取出一个 work;
执行 work->func(work);
}

项目workqueuekthread worker
线程系统共享私有线程
实时性
CPU 绑定一般
调试性一般
场景普通异步任务高性能 IO

同一个 work 未执行完再次 queue,通常失败。

可能导致回调访问已释放对象。

可以。因为运行在线程上下文。


Terminal window
ps -ef | grep demo
cat /proc/<pid>/stack
cat /proc/<pid>/sched

  • workqueue = 系统线程池
  • kthread worker = 私有线程池(单线程版)
  • 高性能驱动优先考虑 kthread worker
  • 普通异步任务使用 workqueue 即可

include/linux/kthread.h
kernel/kthread.c

重点函数:

  • kthread_create_worker
  • kthread_worker_fn
  • kthread_queue_work
  • kthread_flush_work
  • kthread_destroy_worker