Search

Kernel Thread Creation - 3

In  the previous posts about kernel threads, the threads that we created exited by themselves and there was no need to call kthread_stop .
Let us look at an example where we will make the thread wait as long as kthread_stop is not called.

Once the job of the thread is done, if we want the thread to wait until kthread_stop is called, we need to make use of kthread_should_stop call. This function keep polling for kthread_stop and returns "TRUE" only when kthread_stop is called.
Hence in our example code we will change the state of the thread from "RUNNING" to "TASK_INTERRUPTIBLE" once our job is over and keep waiting in a loop as long as kthread_stop is not called.

The only difference will be the addition of the following code in the function that executes as the thread

set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop())
{
   schedule();
   set_current_state(TASK_INTERRUPTIBLE);
}
set_current_state(TASK_RUNNING);


The schedule is used to let the processor do some thing else while this thread waits for the call. But the kernel will schedule this thread again at some time, when the state of the thread will become "RUNNING". Thus before calling schedule again we change the state to TASK_INTERRUPTIBLE .
Hence the modified thread_fn function looks as follows , the rest of the code is same as in Kernel Threads -1

#################################################
int thread_fn() {

unsigned long j0,j1;
int delay = 60*HZ;
j0 = jiffies;
j1 = j0 + delay;

while (time_before(jiffies, j1))
        schedule();
printk(KERN_INFO "In thread1");


set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop())
{
   schedule();
   set_current_state(TASK_INTERRUPTIBLE);
}
set_current_state(TASK_RUNNING);

return 0;
}


###################################################

2 comments:

  1. is that mean schedule() blocks this process at that time?

    ReplyDelete
  2. @monaeuri you can say the process is put to sleep, until kthread_stop is not called.

    ReplyDelete