Search⌘ K
AI Features

Executing Subroutines and Coroutines on the CPU

Explore how CPUs use registers, the stack, and the program counter to execute subroutines and coroutines. Understand call frames, calling conventions, and differences between stackful and stackless coroutines to gain deeper insight into coroutine suspension and resumption in C++.

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 ...