Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resuming the thread after schedule()

Tags:

linux-kernel

Another newbie question:

In the following code, what if the thread is preempted after calling 'set_current_state' but before 'schedule' is called. When the code is scheduled again, does it start from 'schedule' call and is removed from the run queue? Or the 'schedule' call is ignored this time and starts from the set_current_state(TASK_RUNNING) statement?

{
...
set_current_state(TASK_INTERRUPTIBLE); /* suppose thread is preempted just after this function call */
schedule();
set_current_state(TASK_RUNNING);
...
} 
like image 241
Albert Avatar asked Dec 11 '25 23:12

Albert


1 Answers

Here's (more or less) what will happen if involuntary preemption happens after the first line and before the second:

  1. The scheduler will run (scheduler() function from sched.c) - since this is what being preempted mean.

  2. Since your task is marked as not runnable, the scheduler will remove it from the run queue and will pick another task.

  3. Now your task will not be scheduled until something external will mark it as runnable again. This might happen due to a signal sent to the task or, assuming the task is queued in a wait queue, due to the event the wake queue belongs to happening, but something external MUST mark the task as runnable again or it will never be scheduled. This is why if you look at the wait queue code, it first put the task on the wait queue and only then does something similar to your code.

  4. When your task is marked as runnable, at some point the scheduler will pick it and will context switch into the task code.

  5. Then the schedule() function will get called. In all likelihood, the scheduler is going to pick the same task yet again, since it has just been picked by it as most eligible for running and it is not likely that this have changed.

  6. On the way back from the scheduler, the last set_current_state will basically be a no op, since the task by this time is already marked as runnable in this scenario.

like image 118
gby Avatar answered Dec 16 '25 23:12

gby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!