The Challenge of Multitasking
The Z80 is a single-core processor; it can only execute one instruction at a time. Multitasking is the technique of quickly switching the CPU’s attention between several active programs (processes), making it appear as though they are all running simultaneously.
Cooperative Multitasking (The Z80 Standard)
The simplest and most common form of multitasking on an 8-bit OS is Cooperative Multitasking.
The Principle: The CPU runs a program until that program voluntarily yields (gives up control) back to the OS scheduler.
How it Works:
- The scheduler runs Process A.
- Process A finishes its short task (e.g., drawing one sprite or reading one byte).
- Process A executes a specific OS system call (`RST SCHED_YIELD′).
- The OS scheduler then runs Process B.
- Process B eventually yields back to the scheduler.
- The cycle repeats.
Advantage: Simple to implement. Disadvantage: A single misbehaved program that never yields will lock up the entire system.
Time-Slicing (The Advanced Method)
For more robust multitasking, the OS uses a Time-Slicing Scheduler.
The Principle: The CPU is interrupted by a timer interrupt at a fixed frequency (e.g., 50 or 60 times per second), forcing the CPU to stop the current process and switch to the next one, regardless of whether the process is finished.
The Scheduler’s Job (ISR):
TIMER_ISR:
DI ; Disable interrupts
PUSH AF, BC, DE, HL ; 1. Save the state (context) of the current process
CALL FIND_NEXT_PROCESS; 2. Determine which process (B, C, or D) runs next
CALL LOAD_CONTEXT ; 3. Load the saved registers of the next process
EI ; Re-enable interrupts
RETI ; Return to the newly loaded process
Context Switching
The act of saving all the registers (AF, BC, DE, HL, etc.) from the old process to memory and loading the registers for the new process is called a Context Switch.
Optimization: The Z80’s EXX′** (Part 8) and **
EX AF, AF’′ instructions are used heavily in time-slicing schedulers to swap registers rapidly, minimizing the time spent on the context switch overhead.