Cooperative scheduler

Different policies can be defined to alternate the execution of the tasks in the system. In the simplest case, the main functions of each task voluntarily suspend its execution, by invoking the schedule macro.

In this example implementation, two threads are defined. Both will turn on an LED and hold the CPU in a busy-loop for one second, then turn off the LED, and explicitly call the schedule() function to trigger a context switch:

void task_test0(void *arg)
{
uint32_t now = jiffies;
blue_led_on();
while(1) {
if ((jiffies - now) > 1000) {
blue_led_off();
schedule();
now = jiffies;
blue_led_on();
}
}
}

void task_test1(void *arg)
{
uint32_t now = jiffies;
red_led_on();
while(1) {
if ((jiffies - now) > 1000) {
red_led_off();
schedule();
now = jiffies;
red_led_on();
}
}
}

The little operating system is finally working, and the kernel is scheduling the two tasks in sequence. The task with ID 0 is also being resumed at the beginning of each loop, but in this simple case, the kernel task is only calling the schedule in a loop, immediately resuming the task with ID 1. With this design, the reactivity of the system depends entirely on the implementation of the tasks, as each task can hold the CPU indefinitely, and prevent other tasks from running. The cooperative model is only used in very specific scenarios, where each task is directly responsible of regulating its own CPU cycles and cooperating with the other threads, and may impact on the responsiveness and the fairness of the entire system.

For the sake of simplicity, this implementation does not take into account the wrap-around of the jiffies variable. If incremented every millisecond, jiffies would in fact overflow its maximum value after about 42 days. A real operating systems, unlike our simplistic example, must implement an appropriate mechanism to compare time variables, not shown here, that can detect that the wrap-around while calculating time differences.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset