How does a CPU work
The ALU that handles calculation, the instruction that decides what to do. How do these two move as one body? Let's follow the flow of a CPU processing instructions one by one.
A CPU repeats three beats
What a CPU does
is actually simple.
Fetch one instruction,
decode what instruction it is,
execute it.
Then fetch the next one.
It repeats these three beats
without rest.
Fetch → decode → execute, and repeat.
Fetch, decode, execute.
Call this one beat,
and a CPU spins this beat
billions of times a second.
Each one is simple,
but it's so fast
that it does complex things.
A finger pointing at the next instruction
But how does a CPU know
which instruction
it's time to do now?
Somewhere in memory
instructions sit in a row,
and something points
at the "next one to do."
It's the PC, the program counter.
The PC points at the next instruction.
Each time it fetches an instruction,
the PC grows by one.
Did 0, now 1,
did 1, now 2.
Thanks to this finger,
a CPU doesn't lose its place
and does instructions in order.
Parts gather and become a CPU
Now the parts gather.
The PC pointing at the next,
the decoder unpacking the instruction,
the ALU calculating,
small slots holding values for a moment.
Small on their own,
but gathered they become
one CPU that processes instructions.
One CPU body.
The PC points at the next,
the decoder unpacks the instruction,
the ALU calculates,
the register holds the value.
Each does its own job
and spins one beat together.
This is what a CPU at work looks like.
Run three lines of instruction yourself
Here's a short program.
"Hold 3,"
"add 4,"
"show the result."
Step through one beat at a time
and watch the PC move,
the value pile up,
together.
Press to step.
Run line by line, following the PC.
As the PC grew 0, 1, 2,
it ran each instruction, right?
The value became 3,
then 7,
and at the end it showed on screen.
This is what a program
running looks like.
When the PC jumps elsewhere
The PC usually
moves one step at a time,
but sometimes it jumps elsewhere.
Meet an instruction like
"go to instruction 5,"
and the PC changes to that address.
When this "skip"
meets the true or false of comparison from last time,
it becomes the fork called "if."
The PC jumps from 2 to 5.
Instead of going one step at a time,
change the PC to another value
and the program's flow changes.
Skip ahead,
or go back.
Next time we'll see
how this jump becomes
"if" and "repeat."