Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it neccessary to use kthread_stop if we return from kernel thread?

If I have the following kernel thread function:

int thread_fn() {
    printk(KERN_INFO "In thread1");    
    return 0;
}

Do I still need to use kthread_stop() function here?

Will return in the thread function make the kernel thread stop and exit?

like image 700
valmiki Avatar asked Oct 31 '22 06:10

valmiki


1 Answers

If you look at how kthread() is implemented, at line 209 it calls threadfn(data) and stores the exit code in ret; then it calls do_exit(ret).

So a simple return from your threadfn is sufficient.

If you look at the documentation of kthread_stop, it says that it:

  • sets kthread_should_stop to return true;
  • wakes the thread;
  • waits for the thread to exit.

This means that kthread_stop() should be only called from outside a thread to stop the thread. Since it waits for the thread to finish, you must not call this inside the thread or you might deadlock!

Moreover, the documentation says that it only informs the thread that it should exit, and that the thread should call kthread_should_stop to find out about this. So a long-lived threadfn might do this:

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;
}

But if your function is not long-lived, calling kthread_should_stop is not necessary.

like image 181
o9000 Avatar answered Nov 09 '22 13:11

o9000