electronics engineering
Course handbook · Third year
Computer Systems
Computer systems: the multilevel virtual machine model, processor architecture, assembly, memory and input/output.
- 9Topics
- 0Solved exercises
- 9Formula sheet
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/elaboration-systems. Links work in the PDF too.
1Computer organisation and performance
A computer, from the microcontroller in a washing machine to a server processor, executes a sequence of instructions taken from memory. The basic organisation is still the one proposed by von Neumann in 1945; what has changed enormously is how it is built to go fast. In this lesson we cover the von Neumann model, the instruction cycle, how performance is measured and Amdahl’s law, which says how much can be gained from an improvement.
The von Neumann model

- The CPU contains the control unit (CU), which interprets instructions and drives everything else; the arithmetic logic unit (ALU), which does the calculations; the registers, tiny very fast memories. Two special registers: the program counter (PC) with the address of the next instruction and the instruction register (IR) with the one being executed.
- The main memory holds both data and instructions: this is the stored-program idea, which makes the computer universal (changing task means loading another program, not rewiring the machine).
- The input and output (I/O) devices and the bus connecting everything.
In the Harvard architecture instructions and data live in separate memories, with two buses: an instruction and a data item can be read at the same time. Many microcontrollers and signal processors use it; modern processors are von Neumann towards main memory, but have separate caches for instructions and data.
The instruction cycle
The CPU repeats forever:
- fetch: read from memory the instruction at the address held in the PC and place it in the IR; the PC moves on to the next instruction;
- decode: the control unit works out which instruction it is and reads the operands from the registers;
- execute: the ALU computes, or memory is read or written;
- write back the result into a register.
A jump modifies the PC, and the next fetch continues from another point of the program: this is how loops, conditions and function calls are implemented. Everything is paced by a clock, a periodic signal whose frequency (a few gigahertz today) sets the rhythm of the circuits.
Measuring performance
The execution time of a program is
![]()
where
is the number of instructions executed and CPI the average number of clock cycles per instruction.
Example.
instructions, average CPI 1.5, 3 GHz clock:
s.
The three factors depend on different things:
on the algorithm, the compiler and the instruction set; CPI on the processor organisation (pipeline, caches); frequency on the technology and the pipeline depth. Improving one often worsens another, which is why frequency alone does not say which processor is faster. An honest comparison measures time on real programs (benchmarks).
Amdahl’s law
Theorem. If a fraction
of the execution time is sped up by a factor
, the overall speedup is
![]()
and it never exceeds
, however large
is.
Proof. The original time, normalised to 1, splits into a part that is not sped up,
, and a sped-up part
, which becomes
. The new time is
, and the speedup is the ratio of old to new time. As
the denominator tends to
. ∎
Examples.
- Speeding up by 4 times a part taking 80% of the time:
. Even with infinite speedup it cannot exceed
. - A program that is 95% parallelisable on 16 cores:
; with infinitely many cores, at most 20.
The practical lesson: optimise the common case, and the part that stays slow always ends up dominating. Before optimising a program, measure where the time actually goes (with a profiler) instead of guessing.
The rest of the course
The next lessons follow the path of an instruction: how it is encoded (instruction set), how hardware does arithmetic, how the processor executes it (datapath and pipeline), where it finds the data (caches and virtual memory), how it talks to the outside world (input and output) and how several processors work together (parallelism).
2Instruction set architecture and assembly
The instruction set architecture (ISA) is the contract between software and hardware: the list of instructions a processor can execute, how they are encoded in bits, which registers exist and how memory is addressed. A program compiled for an ISA runs on any processor implementing it, from the cheapest to the fastest. In this lesson we use RISC-V, an open, modern ISA, as the example and compare it with more complex architectures.
RISC and CISC
- CISC (Complex Instruction Set Computer) architectures, such as the x86 of PCs, have highly varied instructions of variable length, which can operate directly on memory and do many things at once.
- RISC (Reduced Instruction Set Computer) architectures, such as ARM and RISC-V, have few simple, regular instructions, all the same length; only load and store instructions access memory, and all calculations happen between registers.
RISC programs need more instructions, but each is simpler to decode and to execute in a pipeline:
grows, CPI and clock period fall. Today the distinction is blurred: x86 processors internally translate complex instructions into RISC-like micro-operations, and phones and many laptops use ARM processors.
RISC-V registers
32-bit RISC-V (RV32I) has 32 registers of 32 bits, from x0 to x31. Register x0 is always zero, and writing it has no effect: it looks wasteful, but it gives many operations without dedicated instructions (copying a register is adding zero to it). By convention the others have precise roles: ra for the return address, sp for the stack pointer, a0 to a7 for function arguments, t0 to t6 for temporaries, s0 to s11 for values to be preserved.
Instruction encoding
All instructions are 32 bits long and come in a few formats, with fields in the same places, so decoding is fast. The R format is for register-to-register operations:

Example. add x5, x6, x7 (that is
): opcode 0110011 (register operation), rd = 5, rs1 = 6, rs2 = 7, funct3 and funct7 zero (add, not subtract). Lining up the bits gives the word 0x007302B3: this is the number the processor finds in memory.
The other formats: I for operations with a constant and for loads (12 bits of constant in place of rs2 and funct7), S for stores, B for conditional branches, U and J for large constants and long jumps.
Addressing modes
RISC-V has very few:
- immediate: the constant is in the instruction,
addi t0, t0, 4; - register:
add a2, a2, t0; - base plus offset: the address is a register plus a constant,
lw t0, 8(a0)reads the word at address
. This is enough to access array elements and structure fields; - PC-relative: branches say how far to move from the current instruction, so code works wherever it is placed in memory.
CISC architectures add richer modes (indirect, scaled index, auto-increment), which save instructions but complicate the hardware.
An example program
The sum of the elements of an integer array. In C:
int sum(int *v, int n) {
int s = 0;
for (int i = 0; i < n; i++)
s += v[i];
return s;
}In RISC-V assembly, with a0 = array address, a1 = number of elements, result in a0:
sum: li t1, 0 # s = 0
loop: beqz a1, done # if n == 0 exit
lw t0, 0(a0) # t0 = *v
add t1, t1, t0 # s += t0
addi a0, a0, 4 # v++ (an int takes 4 bytes)
addi a1, a1, -1 # n--
j loop
done: mv a0, t1 # return value
retYou can see the compiler’s work: the index has disappeared, replaced by a pointer that advances by 4 bytes; the loop uses five instructions per element. Each instruction does a single thing, and that is precisely why the processor can execute several of them overlapped.
Function calls and the stack
jal ra, f jumps to function f saving the return address in ra; ret (that is jalr x0, 0(ra)) goes back. If a function calls another, it must save ra and the s registers it uses in a memory area managed as a stack, the stack: space is made by subtracting from sp and restored at the end. The rules on which registers to preserve form the calling convention, which lets separately compiled functions, even in different languages, call each other.
3Computer arithmetic
The arithmetic logic unit does its sums with logic gates. In Foundations of Computer Science we saw how numbers are represented in binary and in two’s complement; here we see how hardware adds, subtracts, detects errors and multiplies, and why the way carries propagate decides a processor’s speed.
The full adder
Adding two binary numbers column by column requires, for each bit, adding three digits: the two bits
and
and the carry
from the previous column. The result is a sum bit
and a carry
for the next column.
Theorem.
![]()
Proof. Check it on the truth table of the eight combinations.
is 1 when the number of inputs at 1 is odd (1 or 3), which is the definition of the exclusive OR of three bits.
is 1 when at least two inputs are 1: either
and
both are (
), or exactly one of them is (
) and
is too. The two cases are disjoint and cover every possibility. ∎

Carry propagation
Placing
full adders in a row, with each carry output connected to the next carry input, gives the ripple-carry adder. It is simple, but slow: the most significant bit is not valid until the carry has travelled the whole chain. If each stage adds a delay of two gates, a 64-bit adder accumulates 128, far too many for a processor running at a few gigahertz.
Carry lookahead
For each column two signals are defined that depend only on
and
:
![]()
The column generates a carry on its own if both bits are 1; it propagates the incoming one if exactly one is 1. So
, and substituting:
![]()
Each carry is computed directly from the inputs, with two levels of gates, without waiting for the previous ones. The gates become very wide as
grows, so one works in groups of 4 bits and repeats the idea hierarchically: the delay grows as
instead of
. The adders of modern processors are variants of this idea (prefix adders, such as Kogge-Stone).
Subtraction and overflow
In two’s complement,
is obtained by inverting all bits and adding 1. So
![]()
and the same adder also subtracts: just put XOR gates on the
inputs (to invert them when needed) and set the initial carry
to 1. This is one reason two’s complement has displaced every other representation of negative numbers.
Overflow. Adding two numbers of the same sign, the result can fall outside the representable range: with 8 bits,
exceeds 127 and appears as −56. It is recognised because the sign of the result differs from that of both addends; in hardware, equivalently, the carry into the most significant bit differs from the carry out of it:
.
The ALU reports the outcome of operations with a few status bits, the flags: Z (zero result), N (negative), C (carry, useful for unsigned numbers), V (overflow, for signed ones). The conditional branches of architectures that use them rely on these bits.
Multiplication
Binary multiplication is simpler than decimal: each partial product is either the multiplicand or zero, depending on the multiplier bit, shifted to the corresponding position. The
partial products are then added.
- The slowest method, shift and add, uses a single adder for
cycles. - Tree multipliers add all partial products together with adders arranged in a tree (Wallace trees), and multiply two 64-bit numbers in a few clock cycles.
Division is harder and is done with iterative algorithms producing one or more quotient digits per cycle: that is why, in speed-critical programs, compilers replace divisions by constants with multiplications and shifts. Floating-point numbers (IEEE 754 standard, Numerical Analysis lesson) have a dedicated unit, which aligns the exponents, operates on the mantissas and normalises the result.
4Datapath and control unit
Inside the processor, instructions are executed by a datapath: registers, memories, ALU, multiplexers and the connections between them. The control unit decides, instruction by instruction, which routes to open. In this lesson we build the datapath of a simple RISC-V processor that executes each instruction in a single clock cycle, and we see why this solution is slow.
The components
- The program counter (PC), a 32-bit register.
- The instruction memory (IMEM): given an address, it returns the instruction.
- The register file (REG): 32 registers, with two read ports (for the two operands) and one write port, all usable in the same cycle.
- The immediate generator (IMM): it extracts the constant from the instruction fields and sign-extends it to 32 bits.
- The ALU, with a control input selecting the operation.
- The data memory (DMEM), for loads and stores.
- An adder computing PC + 4, the address of the next instruction.
- A few multiplexers, which choose between two possible sources of a value.

The path of an instruction
add x5, x6, x7
- The PC addresses the instruction memory.
- The fields rs1 = 6 and rs2 = 7 select two registers, read in parallel.
- The multiplexer in front of the ALU picks the second register (not the constant); the ALU adds.
- The data memory is not used; another multiplexer picks the ALU result, which is written into register rd = 5.
- The PC becomes PC + 4.
lw x5, 8(x6): the ALU adds register x6 and the constant 8 (this time the multiplexer picks the constant) and computes the address; the data memory reads the word; the final multiplexer picks the data read, which goes into x5.
sw x5, 8(x6): the same address calculation, then the memory writes the value of x5; no register is written.
beq x5, x6, label: the ALU subtracts the two registers and signals whether the result is zero; in that case the PC receives PC plus the constant (the branch offset) instead of PC + 4. This needs a second adder and another multiplexer on the PC.
The control unit
The control unit reads the opcode (and funct3, funct7) and produces the control signals: which operation the ALU performs, whether the second operand is a register or the constant, whether a register is written, whether memory reads or writes, where the data to write comes from, whether the PC branches. In a single-cycle processor it is a simple combinational network, a table mapping each instruction type to signal values:
| Instruction | ALU | Second operand | Writes register | Memory | Data written |
|---|---|---|---|---|---|
| add | add | register | yes | none | ALU |
| addi | add | constant | yes | none | ALU |
| lw | add | constant | yes | read | memory |
| sw | add | constant | no | write | |
| beq | subtract | register | no | none |
Why single-cycle is slow
In one clock cycle the longest instruction must complete, the load, which goes in sequence through instruction memory, register file, ALU, data memory and back to the register file. Suppose delays of 200 ps for each memory, 100 ps for register read, 150 ps for the ALU, 50 ps for write-back: the cycle must last at least
ps, that is about 1.4 GHz. An add, which does not use the data memory, would finish in 500 ps, but must still wait for the end of the cycle.
There are two solutions. Multicycle splits execution into shorter steps and uses only the ones each instruction needs. The pipeline, which we will see in the next lesson, splits the datapath into stages and makes them work simultaneously on different instructions: it is the solution of every modern processor, from microcontrollers to servers.
5Pipelining
In a laundry with a washer, a dryer and an iron, you do not wait for the first load to be ironed before putting the second in the washer: while the first dries, the second washes. Each load takes the same time, but one comes out every stage instead of every three. This is the idea of the pipeline: the datapath is split into stages, and each stage works on a different instruction. In this lesson we look at the classic five-stage pipeline, how much it gains and the hazards that slow it down.
The five stages
- IF (fetch): reads the instruction and computes PC + 4;
- ID (decode): decodes and reads the registers;
- EX (execute): the ALU computes the result or the address;
- MEM (memory): reads or writes data memory;
- WB (write back): writes the result into the register file.
Between one stage and the next there are pipeline registers, which hold intermediate results and pass them to the next stage on the clock edge.

The gain
The clock period is now that of the slowest stage (about 200 ps in the example of the previous lesson, instead of 700).
Theorem. With
stages of equal duration,
instructions take
cycles, and the speedup over non-pipelined execution is
![]()
Proof. The first instruction comes out after
cycles; from then on one comes out every cycle, so the other
take
more cycles. Without a pipeline each instruction takes
cycles of the same period, that is
in total. ∎
With 5 stages and a million instructions the speedup is practically 5. The pipeline does not make a single instruction faster (it actually slows it slightly because of the extra registers), but it increases the number of instructions completed per unit time.
In practice the stages are not perfectly balanced and, above all, there are hazards, situations in which an instruction cannot proceed to the next cycle.
Data hazards
add x5, x6, x7
sub x8, x5, x9 # uses x5, which add has not written yetadd writes x5 in the WB stage, in the fifth cycle; sub reads it in the ID stage, in the third. Without countermeasures it would read the old value.
- Forwarding: the result is already available at the ALU output at the end of the third cycle; a multiplexer carries it directly to the ALU input for the next instruction, bypassing the register file. It solves most cases without losing cycles.
- Load followed by use: with
lw x5, 0(x6)followed by an instruction using x5, the data only arrives at the end of the MEM stage, too late for the next instruction’s EX. A one-cycle stall is needed (a “bubble” in the pipeline). The compiler often reorders instructions to fill that slot with an independent one.
Control hazards
A conditional branch is resolved only in the EX stage: meanwhile the pipeline has already fetched the following instructions, which may be the wrong ones. If the branch is taken they must be discarded, and two cycles are lost.
The solution is branch prediction: the processor guesses whether the branch will be taken and fetches accordingly; if it guesses wrong, it discards the work done. Modern predictors remember the past behaviour of each branch and guess right more than 95% of the time: a for loop always branches back, except on the last iteration.
Example. In a program 20% of instructions are loads, half of them immediately followed by a use (1 stall cycle); 15% are branches, mispredicted 10% of the time (2 cycles lost). The average CPI is
![]()
close to the ideal value of 1.
Beyond the simple pipeline
- Deeper pipelines: more, shorter stages allow higher frequencies, but raise the cost of mispredictions. Current processors have 10 to 20 stages.
- Superscalar: several pipelines in parallel, issuing two, four or more instructions per cycle (CPI below 1).
- Out-of-order execution: the processor looks ahead dozens of instructions and runs first those whose operands are ready, while the others wait for data from memory; results are then made visible in the original order.
All of this is invisible to the programmer: the program behaves as if instructions were executed one at a time, in the order written.
6Caches and the memory hierarchy
A modern processor executes an instruction in less than a nanosecond, but reading a value from main memory (DRAM) takes about 80 ns: without countermeasures it would spend nearly all its time waiting. The solution is a memory hierarchy: small, very fast memories close to the processor, large and slow ones further away. It works thanks to a property of programs, locality. In this lesson we see how a cache is built, how the average access time is computed and how the way code is written changes its effectiveness.
The hierarchy

Fast memories (SRAM, in caches) are expensive per bit and take a lot of area; large ones (DRAM, flash) are cheap but slow. Each level holds a copy of the most recently used parts of the level below.
Locality
- Temporal locality: a recently used item will probably be used again soon (the variables of a loop, the instructions of the loop itself).
- Spatial locality: if an item is used, nearby ones probably will be too (the next elements of an array, the next instructions).
To exploit the latter, the cache copies not single bytes but blocks (or lines) of 64 bytes: reading the first element of an array also brings the following ones into the cache.
The direct-mapped cache
Each memory block can live in only one cache line, chosen by part of the address. The address is split into three fields.
Example. A 32 KiB cache with 64-byte blocks and 32-bit addresses: there are
lines.
- offset (6 bits, since
): which byte within the block; - index (9 bits, since
): which cache line; - tag (the remaining
bits): which of the many blocks mapping to that line is present.

Each line holds the block, the tag and a valid bit. On access, the index picks the line and the tag is compared: if it matches (and the line is valid) it is a hit, otherwise a miss: the block is read from the level below and replaces the one present.
Average memory access time
![]()
where
is the miss rate and
the time to fetch the block.
Example. A 1-cycle cache, 5% misses, 100 cycles to reach DRAM: AMAT =
cycles. Adding a 10-cycle second-level cache that finds 80% of the blocks missed in the first level: AMAT =
cycles. The second level more than halves the average time.
Even miss rates that look small weigh heavily: going from 2% to 4% misses, with a 100-cycle penalty, takes AMAT from 3 to 5 cycles.
Associativity and types of miss
In a direct-mapped cache, two blocks used alternately that map to the same line keep evicting each other.
-way set-associative caches let each block live in
different lines (a set), comparing
tags in parallel, and when the set is full they replace the least recently used block (LRU). First-level caches are typically 8-way.
Misses are classified as the “three Cs”: compulsory (the first access to a block), capacity (the data in use do not all fit), conflict (blocks competing for the same set).
Writes. With a write-through policy every write also goes to the level below; with write-back only the cache is written, and the modified block (marked by a “dirty” bit) is copied to memory when it is replaced. The latter greatly reduces memory traffic and is what processor caches use.
Code matters
In C, matrices are stored by rows: the elements of a row are contiguous.
/* fast: walks memory in order */
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
s += a[i][j];
/* slow: jumps N elements on every access */
for (j = 0; j < N; j++)
for (i = 0; i < N; i++)
s += a[i][j];The two versions do exactly the same calculations, but with a large matrix the second can be several times slower: each access falls in a different block, and when the same row comes round again its block has already been replaced. Organising data and loops to exploit locality is one of the most effective optimisations of all, and the basis of fast numerical libraries (which work on blocks that fit in the cache).
7Virtual memory
Dozens of programs run together on a computer, and each behaves as if it had all the memory to itself, starting from address zero, unable to read or corrupt the others’. This is the effect of virtual memory: the addresses used by programs are not the physical DRAM addresses, but are translated by the hardware on every access, under the control of the operating system. In this lesson we cover pages, the page table, the TLB and what happens when data is not in memory.
Virtual and physical addresses
Each process’s virtual address space and the physical memory are divided into blocks of equal size: pages (typically 4 KiB). A virtual address splits into
- the virtual page number (VPN), the high bits;
- the offset within the page, the low 12 bits (
).
Translation replaces the virtual page number with a physical page number (PPN) and leaves the offset unchanged.

What it gives
- Isolation and protection: each process has its own table, and cannot even name the pages of others. Each entry carries permissions (read, write, execute, operating-system-only access): writing to a code page or reading a kernel page raises an exception.
- Apparently contiguous memory: a 1 MiB array is contiguous in virtual addresses even if its physical pages are scattered.
- Sharing: libraries used by many programs are in memory only once, mapped into everyone’s virtual space.
- More memory than physically present: rarely used pages can live on disk and come back into memory when needed.
The page table
The operating system keeps for each process a page table in memory: for each virtual page, if present in memory, the physical page number and the permissions.
The size problem. With 48-bit virtual addresses and 4 KiB pages there are
virtual pages; a flat table with 8-byte entries would take
GiB per process. But a process uses only a small part of its space. So multi-level tables are used (four levels in 64-bit x86 and ARM processors): the page number is split into four groups of 9 bits, each indexing a 512-entry table that points to the next-level table, and the tables for unused regions simply do not exist.
The TLB
This way, however, every memory access would need four more to walk the tables. The solution is a small cache dedicated to translations, the TLB (Translation Lookaside Buffer), with a few dozen or hundred associative entries. Thanks to locality, more than 99% of translations find it already there. Only on a miss does the hardware (or the operating system, in some architectures) walk the tables and load the entry into the TLB.
When the operating system switches from one process to another it changes the active page table (a register holding its address), and the previous process’s TLB entries must not be used: either the TLB is flushed, or each entry carries a process identifier.
The page fault
If the table entry says the page is not in memory, the hardware raises an exception, the page fault, and hands control to the operating system, which:
- finds a free physical page, or frees one by writing a rarely used page to disk (if it was modified);
- reads the requested page from disk;
- updates the table and resumes the interrupted instruction, which succeeds this time.
Reading from an SSD takes about 100 µs, hundreds of thousands of clock cycles: an occasional page fault goes unnoticed, but if programs use more memory than is physically present and pages are constantly swapped with the disk (thrashing) the system becomes extremely slow.
The same mechanism, used on purpose, enables very useful tricks: the pages of an open file are loaded only when read (memory-mapped files); after a fork() parent and child share pages until one of them writes to one, and only then is it copied (copy-on-write).
And in microcontrollers?
Small microcontrollers have no virtual memory: a single program, physical addresses, and at most a memory protection unit (MPU) forbidding access to some regions. Virtual memory is needed where several untrusted programs run together, that is in systems with a full operating system such as Linux, Windows, Android.
8Input/output, interrupts and DMA
A processor that does not communicate with the outside world is useless: it must read sensors, keyboards and networks, and drive motors, screens and disks. Input and output devices are slow and unpredictable compared with the CPU, and the problem is how to exchange data with them without wasting time. In this lesson we see how the processor sees devices, the three transfer techniques (polling, interrupts, DMA) and the most common buses.
Talking to a device
Each device has registers: data (the byte received, the one to transmit), status (ready, busy, error), control (speed, mode). In modern systems they are memory-mapped: they occupy reserved addresses, and are read and written with ordinary load and store instructions. In C they are accessed through a volatile pointer, which stops the compiler from removing or reordering the accesses:
#define UART_STATUS (*(volatile uint32_t *)0x40011000)
#define UART_DATA (*(volatile uint32_t *)0x40011004)
#define TX_EMPTY (1u << 7)
void send(char c) {
while (!(UART_STATUS & TX_EMPTY)) { } /* wait until the transmitter is free */
UART_DATA = c;
}This is polling: the CPU checks the status register continuously.
Polling
It is simple and has minimal latency, but it wastes the CPU: while waiting it does nothing else. It is fine when the wait is very short or the CPU has nothing else to do; it is unacceptable for rare, unpredictable events such as a key press, or when many devices must be handled.
Interrupts
With interrupts it is the device that alerts the CPU, by asserting a request line (IRQ). At the end of the current instruction the processor:
- saves the PC and the state;
- jumps to the interrupt service routine (ISR) associated with that interrupt, whose address is in a vector table;
- runs the routine, which reads or writes the device registers;
- restores the state and resumes the program exactly where it stopped.

Interrupts have priorities: a more important one can interrupt the routine of a less important one. The time between the request and the start of the routine is the latency; in real-time systems (motor control, airbags) it must be guaranteed, and in microcontrollers it is measured in tens or hundreds of nanoseconds.
Rules for service routines. They must be short: they do the bare minimum (read the data, flag the event) and leave the rest to the main program, because while they run, interrupts of equal or lower priority wait. Variables shared between routine and program must be declared volatile and accessed carefully, because the routine can arrive at any moment, even in the middle of an operation.
The cost. Each interrupt costs saving and restoring state, a few hundred nanoseconds, or a few microseconds with an operating system. A 10 Gbit/s network card receives over a million packets per second: at 2 µs per interrupt it would need 2 seconds of CPU every second, impossible. So interrupts are coalesced (one every many packets) and DMA is used.
DMA
With direct memory access (DMA) a dedicated controller transfers blocks of data between the device and memory without the CPU. The processor programs the transfer (start address, amount, direction) and carries on with other work; the DMA controller uses the bus on its own and, at the end, raises a single interrupt. This is how disks, network cards, high-speed analogue-to-digital converters and audio are read.
There is a delicate detail: DMA writes to memory, but the CPU may hold an old copy of that data in its cache. Architectures solve this with cache coherence towards devices, or software must flush or invalidate the cache before and after the transfer.
Buses
| Bus | Typical use | Characteristics |
|---|---|---|
| I²C | sensors, small memories | 2 wires, up to a few Mbit/s, many addressed devices |
| SPI | displays, converters, flash memories | 4 wires, tens of Mbit/s, simple and fast |
| UART | console, radio modules, GPS | 2 wires, asynchronous, up to a few Mbit/s |
| CAN | cars, industry | 2 differential wires, robust to noise, message priorities |
| USB | computer peripherals | from 12 Mbit/s to tens of Gbit/s, power included |
| PCI Express | graphics cards, SSDs, networking | point-to-point serial links, up to tens of GB/s with several lanes |
The trend is clear: parallel buses with many wires have been replaced almost everywhere by fast serial links, because at high frequencies it is impossible to keep dozens of signals aligned with each other (Electromagnetic Fields lesson on transmission lines).
9Parallel processing
Until the early 2000s programs got faster on their own, with each new processor generation, thanks to higher frequencies. Then frequency stopped rising (Electronic Devices lesson on CMOS logic), and the extra transistors were used to put several processors, the cores, on the same chip. Since then, to go faster, programs must be written to work in parallel. In this lesson we cover threads, the problem of race conditions, synchronisation, cache coherence and the other forms of parallelism.
Multicore processors

Each core is a complete processor, with its own pipeline and private caches; the cores share the last-level cache and memory. The operating system assigns threads to the cores: independent streams of execution, which may belong to different programs or to the same program. Threads of the same program share memory, which is both their strength (they exchange data without copying it) and their danger.
The race condition
Two threads each increment the same counter a million times:
int counter = 0;
void *work(void *arg) {
for (int i = 0; i < 1000000; i++)
counter++;
return NULL;
}The expected result is 2 000 000, but running the program gives lower values, different every time. The reason: counter++ is not a single operation, but three instructions (load, add, store). If both threads load the same value, say 41, before the other has stored, both write 42: one increment is lost. This is a race condition: the result depends on the random order in which the threads run. These bugs are among the hardest to find, because they occur rarely and disappear when you try to observe them.
Synchronisation
- Mutual exclusion (mutex): a lock that only one thread at a time can hold. The part of code accessing shared data, the critical section, is enclosed between
lockandunlock:
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *work(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&m);
counter++;
pthread_mutex_unlock(&m);
}
return NULL;
}- Atomic operations: the hardware provides instructions that read, modify and write a variable indivisibly (in C,
atomic_fetch_add). For a counter they are much more efficient than a mutex.
Synchronisation has a cost and brings new dangers: deadlock, when two threads each wait for a lock held by the other, and loss of parallelism, when threads spend more time waiting for each other than working. The best solution is often to avoid sharing: each thread adds into its own private counter, and only at the end are the partial results added.
Cache coherence
If two cores hold a copy of the same data in their caches and one modifies it, the other must not keep reading the old value. A coherence protocol such as MESI tracks the state of each line in each cache (Modified, Exclusive, Shared, Invalid): before writing, a core invalidates the others’ copies. The programmer does not see it, but pays its effects:
- false sharing: two threads write different variables that sit in the same 64-byte line; the line bounces continuously between the two cores’ caches, and the program slows down a lot without really sharing anything. It is avoided by spacing out data used by different threads.
Other forms of parallelism
- SIMD (single instruction, multiple data): instructions operating on vectors of 4, 8 or 16 numbers at once (SSE, AVX on PCs, NEON on ARM). Compilers use them automatically in simple loops; they are why audio, video and neural networks run fast even on the CPU.
- GPUs: thousands of simple units running the same program on different data. Born for graphics, they have become the engine of scientific computing and artificial intelligence. They work very well on highly regular problems with lots of data, poorly on code full of conditions.
- Instruction-level parallelism: the kind exploited automatically by superscalar and out-of-order processors (lesson on the pipeline).
How much is gained
Amdahl’s law returns: with 95% of the program parallelisable, 16 cores give at most a speedup of 9.1 and infinitely many cores 20. Moreover, threads must synchronise and shared memory has limited bandwidth. Gustafson’s law offers a more optimistic view: in practice, with more cores one does not solve the same problem faster, but a bigger problem in the same time (a finer simulation, an image with more pixels), and there the parallel part grows and the speedup approaches the number of cores.
∑Formula sheet
Computer organisation and performance
Measuring performance
![]()
Amdahl's law
![]()
Computer arithmetic
The full adder
![]()
Carry lookahead
![]()
![]()
Subtraction and overflow
![]()
Pipelining
The gain
![]()
Control hazards
![]()
Caches and the memory hierarchy
Average memory access time
![]()