Executing Subroutines and Coroutines on the CPU
Learn how CPU registers, instructions, and stacks are used for executing subroutines and coroutines, including call and return, as well as suspending and resuming stackless coroutines.
We have talked about memory hierarchies, caches, virtual memory, scheduling of threads, and other hardware and operating system concepts in this course. But we haven’t really talked about how instructions are executed on the CPU using CPU registers and the stack. These concepts are important to understand when comparing subroutines with various flavors of coroutines.
CPU registers, instructions, and the stack
This lesson will provide a very simplified model of a CPU for the purpose of understanding context switching, function calls, and a few more details regarding the call stack. When we say CPUs in this context, we refer to some CPUs that are similar to the x86 family of CPUs equipped with multiple general-purpose registers.
A program contains a sequence of instructions that the CPU executes. The sequence of instructions is stored somewhere in the memory of the computer. The CPU keeps track of the address of the currently executing instruction in a register called a program counter. In that way, the CPU knows what instruction to execute next.
The CPU contains a fixed number of registers. A register is similar to a variable with a predefined name that can store a value or a memory address. Registers are the fastest data storage available on a computer and sit closest to the CPU. When the ...