دانلود کتاب Programming Embedded Systems in C and C ++
by Michael Barr
|
عنوان فارسی: برنامه نویسی سیستم های تعبیه شده در C و C ++ |
دانلود کتاب
جزییات کتاب
8.2.3 Context Switch
The actual process of changing from one task to another is called a context switch. Because contexts are processor-specific, so is the code that implements the context switch. That means it must always be written in assembly language. Rather than show you the 80x86-specific assembly code that I used in ADEOS, I'll show the context switch routine in a C-like pseudocode:
void
contextSwitch(PContext pOldContext, PContext pNewContext)
{
if (saveContext(pOldContext))
{
//
// Restore new context only on a nonzero exit from saveContext().
//
restoreContext(pNewContext);
// This line is never executed!
}
// Instead, the restored task continues to execute at this point.
}
The contextSwitch routine is actually invoked by the scheduler, which is in turn called from one of the operating system calls that disables interrupts. So it is not necessary to disable interrupts here. In addition, because the operating system call that invoked the scheduler is written in a high-level language, most of the running task's registers have already been saved onto its local stack. That reduces the amount of work that needs to be done by the routines saveContext and restoreContext. They need only worry about saving the instruction pointer, stack pointer, and flags.
The actual behavior of contextSwitch at runtime is difficult to see simply by looking at the previous code. Most software developers think serially, assuming that each line of code will be executed immediately following the previous one. However, this code is actually executed two times, in pseudoparallel. When one task (the new task) changes to the running state, another (the old task) must simultaneously go back to the ready state. Imagine what the new task sees when it is restored inside the restoreContext code. No matter what the new task was doing before, it always wakes up inside the saveContext code-because that's where its instruction pointer was saved.
How does the new task know whether it is coming out of saveContext for the first time (i.e., in the process of going to sleep) or the second time (in the process of waking up)? It definitely does need to know the difference, so I've had to implement saveContext in a slightly sneaky way. Rather than saving the precise current instruction pointer, saveContext actually saves an address a few instructions ahead. That way, when the saved context is restored, execution continues from a different point in the saveContext routine. This also makes it possible for saveContext to return different values: nonzero when the task goes to sleep and zero when the task wakes up. The contextSwitch routine uses this return value to decide whether to call restoreContext. If contextSwitch did not perform this check, the code associated with the new task would never get to execute.