Course outline · 0% complete

0/28 lessons0%

Course overview →

The fetch-decode-execute cycle

lesson 1-2 · ~12 min · 2/28

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:

  1. Fetch the next instruction from RAM. The CPU keeps a counter, called the program counter, that holds the address of the next instruction.
  2. Decode it: figure out what kind of instruction it is (add? copy? jump?).
  3. 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.

1. FETCHread from RAM2. DECODEwhat is it?3. EXECUTEdo the workrepeat, billions of times per second
The fetch-decode-execute cycle. The gold marker shows where the CPU is in the loop.

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/elif chain 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?