如果我们从内核线程返回,是否需要使用kthread_stop?

val*_*iki 5 c linux-device-driver linux-kernel embedded-linux

如果我有以下内核线程函数:

int thread_fn() {
    printk(KERN_INFO "In thread1");    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我还需要在kthread_stop()这里使用功能吗?

return在线程函数使内核线程停止并退出?

o90*_*000 2

如果你看看它kthread()是如何实现的,你会发现它在第 209 行调用了threadfn(data)退出代码并将其存储在ret;中。然后它调用do_exit(ret).

因此,您的简单返回threadfn就足够了。

如果您查看kthread_stop的文档,它会说:

  • 设置kthread_should_stop返回 true;
  • 唤醒线程;
  • 等待线程退出。

这意味着kthread_stop()只能从线程外部调用来停止线程。由于它等待线程完成,因此您不能在线程内调用它,否则可能会死锁!

此外,文档说它只通知线程它应该退出,并且线程应该调用kthread_should_stop来找出这一点。所以长寿者threadfn可能会这样做:

int thread_fn() {
    printk(KERN_INFO "In thread1");
    while (!kthread_should_stop()) {
        get_some_work_to_do_or_block();
        if (have_work_to_do())
            do_work();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但如果您的函数不是长期存在的,kthread_should_stop则无需调用。