2.4 Preemptive Thread Change

Multithreading and Round Robin do not imply preemption. In other words, threads may voluntarily `yield' the processor to the next one in certain Round Robin multithreading schemes. A good1 RTK should also allow preemption of threads.

Preemption is the act of an RTK forcing a thread to give up processor resources and passing processor resources to the next thread. This is quite useful for threads that are compute-bound.

Let us consider our example thread that computes the best path to a destination. Most algorithms for such a task do not have ``convenient'' points to yield. In order for other peer threads to get control, the kernel must force the algorithm to give up control.

For any multithreading implementations using multiple stacks, preemption is relatively easy to add. The easiest way to add preemption is to add the logic to yield in a timer interrupt service routine (ISR). As a timer interrupts, the ISR automatically yields the interrupted thread, and give control to the next peer thread.

This can be done as follows:

This makes the timer ISR ``returns from interrupt'' to the yield subroutine, which performs two actions. First, the reti instruction reenables interrupt. Second, the ``yield'' subroutine saves the context (including the return address to the interrupted thread) and switches to the next thread.

Copyright © 2008-10-25 by Tak Auyeung