Lesson 4 · Operating Systems

Multiprocessor Systems

A multiprocessor system has two or more CPUs that share memory, the bus and devices under one operating system. It raises throughput and reliability, and brings new problems: coherent caches and memory that is not equally close to every CPU.

Multiprocessor Systems concept diagramLeft, UMA (uniform memory access): three CPUs, each with a private cache, share one system bus to a single main memory and I/O, so every CPU has the same access time. Right, NUMA: two nodes, each with two CPUs and its own local memory, joined by an interconnect. Local memory access is fast; access to the other node's memory is slower.UMA (uniform memory access)CPU 0cacheCPU 1cacheCPU 2cachesystem busshared memoryI/Osame access time from every CPUsimple, but the bus limits it to a few dozen CPUsNUMA (non-uniform memory access)CPU 0CPU 1local memorynode ACPU 2CPU 3local memorynode Bnodes joined by an interconnectlocal memory fast, the other node's memory slower
1

Several CPUs Under One Operating System

  1. Several CPUs – two or more processors, each able to run any process.
  2. Shared memory – all processors access a common physical memory.
  3. Shared bus and devices – processors communicate through the bus or interconnect.
  4. One operating system – a single OS image controls all processors and resources.

A multiprocessor system, also called a parallel system or tightly coupled system, has two or more processors in close communication, sharing the computer bus and usually the memory and peripheral devices, all controlled by one operating system. A single-processor system has one general-purpose CPU; a multiprocessor system can execute several processes, or several threads of one process, at the same instant.

Almost every computer sold today is a multiprocessor. Phones and laptops contain multicore chips, several CPUs on one die, and servers combine several such chips. The operating system must therefore schedule across CPUs (multiprocessor scheduling), keep their caches consistent, and protect shared kernel data with locks.

  • Speed-up with N processors is less than N: CPUs wait for locks, the bus and each other
  • A process still runs on one CPU at a time; only multithreaded programs or several processes use the extra CPUs
  • The kernel itself becomes concurrent code, so every shared kernel structure needs a lock
2

Symmetric and Asymmetric Multiprocessing

In symmetric multiprocessing (SMP) every processor is a peer. Each one runs the operating system, schedules itself and performs any task, including kernel work and I/O. Windows, Linux, macOS and Android are all SMP systems. The processors share memory, so the kernel must lock its data structures to prevent two CPUs from modifying them at once.

In asymmetric multiprocessing (AMP) each processor has a specific role. One master processor runs the operating system and assigns work to worker processors, which run only user code or dedicated tasks. It is simpler, because only one processor touches kernel data, but the master is a bottleneck and a single point of failure. AMP survives in embedded systems, where a small processor may handle a radio or audio beside a main CPU.

Symmetric against asymmetric multiprocessing
AspectSMP (symmetric)AMP (asymmetric)
Processor rolesall identical peersone master, the rest workers
Who runs the OSevery processorthe master only
Shared kernel datamust be lockedtouched only by the master
Scalabilitygood, limited by contentionlimited by the master
If one processor failsthe others continuemaster failure stops the system
ExamplesWindows, Linux, macOS, Androidearly multiprocessors, embedded controllers
  • Asymmetric multiprocessing is not the same as heterogeneous cores: a phone with fast and slow cores still runs SMP
  • How the OS assigns work in each: Multiprocessor Scheduling
3

Tightly Coupled and Loosely Coupled Systems

Multiple-processor systems are also classified by how closely the processors are connected. In a tightly coupled system the processors share main memory and a clock and communicate through that memory; this is a multiprocessor in the strict sense. In a loosely coupled system each processor has its own private memory and the processors communicate by passing messages over a network or high-speed link; this is a distributed or clustered system.

The difference matters to the programmer. Threads on a tightly coupled machine can share a variable directly, which is why they need locks. Processes on a loosely coupled system cannot share memory at all and must send each other messages, which makes them independent enough that one machine can fail without stopping the rest.

Tightly against loosely coupled systems
AspectTightly coupledLoosely coupled
Memoryshared main memoryprivate memory per processor
Communicationthrough shared memorymessage passing over a network
Data rate between processorsvery highlower
Operating systemone OS imagean OS per node, often coordinated
Fault isolationa fault can affect the whole machinea node can fail independently
Examplesmulticore PCs, SMP serversclusters, distributed systems
  • Tightly coupled = multiprocessor; loosely coupled = multicomputer
  • A NUMA machine is still tightly coupled: one OS and one address space, only with uneven access times
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Multiprocessor systemTwo or more CPUs sharing memory and devices under one OS.
  • SMP / AMPAll processors equal peers, or one master assigning work to workers.
  • UMA / NUMAEqual memory access for all CPUs, or faster local memory per node.
  • Graceful degradationContinuing to work, more slowly, after a processor fails.

Mechanisms

  • SnoopingEach cache watches the bus and reacts to other CPUs' transactions.
  • MSI / MESICache line states that keep private caches coherent.
  • Directory protocolRecords which nodes hold each line; scales beyond one bus.
  • InterconnectThe links joining NUMA nodes or cluster machines.
Implementation

Cache coherence on a shared bus with MSI

OPS = [
    (0, "read"),
    (1, "read"),
    (0, "write", 6),
    (1, "read"),
    (2, "write", 9),
    (0, "read"),
]


def without_coherence():
    memory, cache = 5, [None, None, None]
    for cpu, op, *value in OPS[:4]:
        if op == "write":
            cache[cpu] = value[0]  # stays in this CPU's cache only
            print(f"  CPU {cpu} writes {value[0]} into its own cache")
        else:
            if cache[cpu] is None:
                cache[cpu] = memory
            print(f"  CPU {cpu} reads x = {cache[cpu]}")
    print(f"  CPU 0 holds {cache[0]}, memory {memory}, CPU 1 read {cache[1]}: stale")


def msi():
    memory = 5
    state, value = ["I"] * 3, [None] * 3
    bus = writebacks = 0
    for cpu, op, *new in OPS:
        others = [c for c in range(3) if c != cpu]
        owner = next((c for c in others if state[c] == "M"), None)
        if op == "read" and state[cpu] == "I":
            bus += 1
            if owner is not None:  # the owner snoops BusRd, writes back, drops to S
                memory = value[owner]
                state[owner] = "S"
                writebacks += 1
            state[cpu], value[cpu] = "S", memory
            note = "BusRd" + (f", CPU {owner} writes back" if owner is not None else "")
        elif op == "read":
            note = "hit, no bus traffic"
        else:
            if state[cpu] != "M":
                bus += 1
                if owner is not None:
                    memory = value[owner]
                    writebacks += 1
                for c in others:
                    state[c], value[c] = "I", None  # invalidate every other copy
                kind = "BusUpgr" if state[cpu] == "S" else "BusRdX"
                note = f"{kind}, others invalidated"
            else:
                note = "hit in M, no bus traffic"
            state[cpu], value[cpu] = "M", new[0]
        shown = " ".join(f"{s}:{'-' if v is None else v}" for s, v in zip(state, value))
        action = f"reads {value[cpu]}" if op == "read" else f"writes {new[0]}"
        print(f"  CPU {cpu} {action:<8} {note:<34} {shown}  memory {memory}")
    print(f"  bus transactions: {bus}, write-backs: {writebacks}")


print("without cache coherence:")
without_coherence()
print("with the MSI protocol:")
msi()
#include <cstdio>
#include <optional>
#include <string>
#include <vector>
using namespace std;

// One shared variable x, three CPUs with private caches, a snooping bus and MSI:
// M = modified (only valid copy, memory stale), S = shared (clean), I = invalid.
struct Op {
    int cpu;
    bool write;
    int value;  // used by writes only
};
const vector<Op> OPS = {
    {0, false, 0}, {1, false, 0}, {0, true, 6}, {1, false, 0}, {2, true, 9}, {0, false, 0},
};

void withoutCoherence() {
    int memory = 5;
    vector<optional<int>> cache(3);
    for (int i = 0; i < 4; i++) {
        const Op& op = OPS[i];
        if (op.write) {
            cache[op.cpu] = op.value;  // stays in this CPU's cache only
            printf("  CPU %d writes %d into its own cache\n", op.cpu, op.value);
        } else {
            if (!cache[op.cpu]) cache[op.cpu] = memory;
            printf("  CPU %d reads x = %d\n", op.cpu, *cache[op.cpu]);
        }
    }
    printf("  CPU 0 holds %d, memory %d, CPU 1 read %d: stale\n", *cache[0], memory, *cache[1]);
}

void msi() {
    int memory = 5, bus = 0, writebacks = 0;
    vector<char> state(3, 'I');
    vector<optional<int>> value(3);
    for (const Op& op : OPS) {
        int cpu = op.cpu;
        int owner = -1;
        for (int c = 0; c < 3; c++) {
            if (c != cpu && state[c] == 'M') owner = c;
        }
        string note;
        if (!op.write && state[cpu] == 'I') {
            bus++;
            if (owner >= 0) {  // the owner snoops BusRd, writes back, drops to S
                memory = *value[owner];
                state[owner] = 'S';
                writebacks++;
            }
            state[cpu] = 'S';
            value[cpu] = memory;
            note = "BusRd" + (owner >= 0 ? ", CPU " + to_string(owner) + " writes back" : string());
        } else if (!op.write) {
            note = "hit, no bus traffic";
        } else {
            if (state[cpu] != 'M') {
                bus++;
                if (owner >= 0) {
                    memory = *value[owner];
                    writebacks++;
                }
                string kind = state[cpu] == 'S' ? "BusUpgr" : "BusRdX";
                for (int c = 0; c < 3; c++) {
                    if (c != cpu) {
                        state[c] = 'I';  // invalidate every other copy
                        value[c].reset();
                    }
                }
                note = kind + ", others invalidated";
            } else {
                note = "hit in M, no bus traffic";
            }
            state[cpu] = 'M';
            value[cpu] = op.value;
        }
        string shown;
        for (int c = 0; c < 3; c++) {
            shown += (c ? " " : "") + string(1, state[c]) + ":" + (value[c] ? to_string(*value[c]) : "-");
        }
        string action = (op.write ? "writes " : "reads ") + to_string(op.write ? op.value : *value[cpu]);
        printf("  CPU %d %-8s %-34s %s  memory %d\n", cpu, action.c_str(), note.c_str(), shown.c_str(),
               memory);
    }
    printf("  bus transactions: %d, write-backs: %d\n", bus, writebacks);
}

int main() {
    printf("without cache coherence:\n");
    withoutCoherence();
    printf("with the MSI protocol:\n");
    msi();
    return 0;
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    // One shared variable x, three CPUs with private caches, a snooping bus and MSI:
    // M = modified (only valid copy, memory stale), S = shared (clean), I = invalid.
    record Op(int cpu, boolean write, int value) {} // value is used by writes only

    static final Op[] OPS = {
        new Op(0, false, 0), new Op(1, false, 0), new Op(0, true, 6),
        new Op(1, false, 0), new Op(2, true, 9), new Op(0, false, 0)
    };

    static void withoutCoherence() {
        int memory = 5;
        Integer[] cache = new Integer[3];
        for (int i = 0; i < 4; i++) {
            Op op = OPS[i];
            if (op.write()) {
                cache[op.cpu()] = op.value(); // stays in this CPU's cache only
                System.out.printf("  CPU %d writes %d into its own cache%n", op.cpu(), op.value());
            } else {
                if (cache[op.cpu()] == null) cache[op.cpu()] = memory;
                System.out.printf("  CPU %d reads x = %d%n", op.cpu(), cache[op.cpu()]);
            }
        }
        System.out.printf("  CPU 0 holds %d, memory %d, CPU 1 read %d: stale%n", cache[0], memory, cache[1]);
    }

    static void msi() {
        int memory = 5, bus = 0, writebacks = 0;
        char[] state = {'I', 'I', 'I'};
        Integer[] value = new Integer[3];
        for (Op op : OPS) {
            int cpu = op.cpu();
            int owner = -1;
            for (int c = 0; c < 3; c++) {
                if (c != cpu && state[c] == 'M') owner = c;
            }
            String note;
            if (!op.write() && state[cpu] == 'I') {
                bus++;
                if (owner >= 0) { // the owner snoops BusRd, writes back, drops to S
                    memory = value[owner];
                    state[owner] = 'S';
                    writebacks++;
                }
                state[cpu] = 'S';
                value[cpu] = memory;
                note = "BusRd" + (owner >= 0 ? ", CPU " + owner + " writes back" : "");
            } else if (!op.write()) {
                note = "hit, no bus traffic";
            } else {
                if (state[cpu] != 'M') {
                    bus++;
                    if (owner >= 0) {
                        memory = value[owner];
                        writebacks++;
                    }
                    String kind = state[cpu] == 'S' ? "BusUpgr" : "BusRdX";
                    for (int c = 0; c < 3; c++) {
                        if (c != cpu) {
                            state[c] = 'I'; // invalidate every other copy
                            value[c] = null;
                        }
                    }
                    note = kind + ", others invalidated";
                } else {
                    note = "hit in M, no bus traffic";
                }
                state[cpu] = 'M';
                value[cpu] = op.value();
            }
            List<String> shown = new ArrayList<>();
            for (int c = 0; c < 3; c++) shown.add(state[c] + ":" + (value[c] == null ? "-" : value[c]));
            String action = op.write() ? "writes " + op.value() : "reads " + value[cpu];
            System.out.printf("  CPU %d %-8s %-34s %s  memory %d%n",
                    cpu, action, note, String.join(" ", shown), memory);
        }
        System.out.printf("  bus transactions: %d, write-backs: %d%n", bus, writebacks);
    }

    public static void main(String[] args) {
        System.out.println("without cache coherence:");
        withoutCoherence();
        System.out.println("with the MSI protocol:");
        msi();
    }
}
Watch it run

Step through it

Running on memory x = 5; CPU 0 read, CPU 1 read, CPU 0 write 6, CPU 1 read, CPU 2 write 9, CPU 0 read

CPU 0cachex not cachedCPU 1cachex not cachedCPU 2cachex not cachedshared busmemory x = 5up to dateno coherence protocolCPU 0 readCPU 1 readCPU 0 write 6CPU 1 read
Step 1

Three CPUs, three private caches, one shared memory

In a shared-memory multiprocessor each CPU has its own cache, so it rarely has to use the shared bus. Memory holds x = 5. First, run the operations with no coherence protocol: each cache simply keeps whatever it loaded.

Output
1 / 13
4

Multiprocessor System Architecture: UMA vs NUMA

A shared-memory multiprocessor can connect its processors to memory in two ways, shown in the diagram at the top. In uniform memory access (UMA), every processor reaches all of memory through the same bus in the same time. It is simple, and it is how most SMP systems with a few cores work. But every memory access crosses the one bus, so adding processors eventually saturates it.

In non-uniform memory access (NUMA), the machine is built from nodes, each with a few processors and its own local memory, joined by an interconnect. A processor can still reach every address, but its local memory is faster than a remote node's. NUMA scales to many more processors; the price is that the OS must place each process's memory on the node where it runs, which is why the scheduler keeps processes near their memory.

UMA against NUMA
AspectUMANUMA
Memory access timethe same for every CPUlocal fast, remote slower
Structureone shared bus and memorynodes with local memory plus an interconnect
Scalabilitya few dozen CPUs at mosthundreds of CPUs
OS concernbus contentionplacing memory on the right node
Typical usedesktops, small serverslarge multi-socket servers
  • Most small SMP machines are UMA; large multi-socket servers are NUMA
  • Linux allocates a page on the node of the CPU that first touches it, and numactl can override the placement
5

Keeping Private Caches Coherent

Each processor has its own cache, so a shared variable can have a copy in several caches at once. When one processor writes its copy, the others become stale. The tracer shows what goes wrong without help: CPU 1 reads 5 after CPU 0 wrote 6. Cache coherence is the guarantee that every read returns the most recent write to that location.

In a bus-based system, coherence is kept by snooping: every cache controller watches the bus and reacts to other processors' transactions. The MSI protocol keeps each line in one of three states; MESI (Intel uses a variant, MESIF) adds an Exclusive state for a clean line only one cache holds, so writing it needs no bus transaction. Large NUMA machines replace snooping with a directory that records which nodes hold each line.

MSI cache line states
StateMeaningOn a write by this CPUWhen another CPU reads
M (Modified)only valid copy, memory is stalewrite locallywrite back, move to S
S (Shared)clean copy, others may sharebroadcast invalidate, move to Mstay S
I (Invalid)no valid copyfetch exclusively, move to Mno action
  • Write-invalidate: a writer removes all other copies first
  • Snooping for buses, directories for large NUMA systems
  • False sharing: two variables in one cache line cause needless invalidations
6

Multicore and Clustered Systems

A multicore processor places several complete cores on one chip. Communication between cores on one die is faster than between separate chips, and one chip with four cores uses much less power than four single-core chips. The OS sees each core, and each hardware thread on a core, as a separate logical CPU. Many chips are also heterogeneous, mixing fast performance cores with small efficiency cores, as in ARM big.LITTLE and Intel's P-cores and E-cores.

A clustered system takes the idea further by joining whole computers, each with its own memory and OS, over a fast network. Clusters are loosely coupled. They provide high availability: if one node fails, another takes over its work. In asymmetric clustering one node stays on hot standby; in symmetric clustering all nodes run applications and monitor each other.

  • Two hardware threads on one core share its execution units, so they give far less than twice the speed of one
  • Cores on one chip usually share the last-level cache, so data passed between them never touches main memory
  • A cluster survives a node failure; a multicore chip fails as a whole
7

Advantages of a Multiprocessor System

Textbooks list three advantages of multiprocessor systems. Increased throughput: more work is done in less time. Economy of scale: processors share the power supply, storage, memory and peripherals, so several CPUs in one box cost less than several computers. Increased reliability: if one processor fails, the others share its work, so the system slows down rather than stopping.

The ability to keep providing service in proportion to the hardware still working is called graceful degradation. Systems that can go further and continue with no loss of service despite a failure are fault tolerant, which requires redundant hardware to detect and correct the failure.

  • Cost: a more complex kernel, with locks, per-CPU run queues and load balancing
  • Cost: the shared bus or memory becomes a bottleneck as CPUs are added
  • Cost: programs gain nothing unless written for concurrency; Amdahl's law says the serial part caps the speed-up (a 10% serial program never runs more than 10x faster)