How the CPU actually runs code
This loop is the ground floor of the whole course: processes (unit 3), race conditions (unit 5), and the scheduler (unit 6) are all things done to this loop, and you cannot reason about any of them without it. It is also why a stack trace or a debugger can tell you "the program was exactly here" — the machine always knows precisely which instruction is next.
The CPU does exactly one thing, forever, billions of times per second:
- Fetch the next instruction from RAM. The CPU keeps a counter, called the program counter, that holds the address of the next instruction.
- Decode it: figure out what kind of instruction it is (add? copy? jump?).
- Execute it: do the work, usually updating a value in a tiny super-fast storage slot inside the CPU called a register.
Then it goes back to step 1. That is the whole trick. Every game, browser, and AI model is just this loop running on very simple instructions, very fast.
A CPU you can read
Real CPU instructions are patterns of bits, but we can simulate the exact same loop in Python. Below, memory is a list of instructions (our fake RAM), pc is the program counter, and acc is a single register called the accumulator.
Watch the three phases in the loop:
- fetch:
instruction = memory[pc], then move the counter forward - decode: split the instruction into an operation and its argument
- execute: the
if/elifchain does the actual work
Run it and check the output.
Code exercise · python
Run this tiny CPU simulator. The program in memory loads 5, adds 3, adds 2, prints the accumulator, and halts.
Code exercise · python
Your turn. Add a SUB instruction to the simulator so the program below prints 6. SUB should subtract its argument from the accumulator.
Quiz
In the simulator, what does the variable pc (the program counter) hold?