Lesson 17 · Processes, threads, and CPU scheduling

Multiprocessor Scheduling

With more than one CPU the scheduler must decide where a task runs as well as when. Keeping caches warm and keeping every CPU busy pull in opposite directions.

Multiprocessor Scheduling concept diagramLeft: a single shared ready queue with arrows to three CPUs, marked as needing one lock. Right: three CPUs, each with its own run queue, and dashed balancer arrows between neighbouring queues for push and pull migration.one shared ready queueT1T2T3T4T5one lock guards every scheduling decisionCPU 0CPU 1CPU 2simple and balanced by design, but the lockcontends and tasks hop between cachesa run queue per CPUT1T2CPU 0T3CPU 1T4T5CPU 2pushpullno shared lock and warm caches;a balancer migrates tasks when queues drift
1

What Is Multiprocessor Scheduling

  1. Who schedules – one master CPU, or every CPU for itself.
  2. Where tasks wait – one shared ready queue, or a queue per CPU.
  3. Where a task runs – ideally where its cache is warm (affinity).
  4. How work spreads – migrating tasks so no CPU idles while others are loaded (load balancing).

Multiprocessor scheduling is CPU scheduling on a multiprocessor system, a machine with more than one processor: several cores on one chip, several chips on one board, or both. A single-CPU scheduler only chooses which ready process runs next. A multiprocessor scheduler also chooses where it runs, and whether to move it later.

The usual assumption is homogeneous processors: every CPU can run every task, so any ready task could run anywhere. Even then the choice matters, because each CPU has its own caches, and a task that moves leaves its cached data behind.

  • Choose when and where a task runs
  • Homogeneous CPUs: any task can run on any CPU
  • Caches make placement matter even when CPUs are identical
2

Asymmetric vs Symmetric Multiprocessing

In asymmetric multiprocessing (AMP) one processor, the master, runs the scheduler and the kernel's data structures; the others run only user code handed to them. Only one CPU touches kernel state, so there is no concurrent access to protect. But the master becomes a bottleneck, and if it fails the system stops.

In symmetric multiprocessing (SMP) every processor runs the kernel and schedules itself. This is what Windows, Linux, macOS and Android all use. It scales, but kernel structures such as ready queues are now shared between CPUs and must be protected with locks.

AMP against SMP
AspectAsymmetric (AMP)Symmetric (SMP)
Who runs the schedulerone master CPUevery CPU
Kernel data sharingnone neededmust be locked
Bottleneckthe masterlock contention
Failure of one CPUmaster failure stops everythingothers continue
Used bysome embedded and early systemsall mainstream operating systems
  • AMP: simple, one scheduler, master is a bottleneck
  • SMP: each CPU self-schedules, shared state needs locks
  • SMP is the standard on every general-purpose OS
3

Common Ready Queue vs Per-CPU Run Queues

An SMP scheduler can keep one common ready queue that every CPU takes from. Load is balanced automatically, because an idle CPU simply takes the next task. The cost is a single lock that every scheduling decision on every CPU must acquire, and tasks bounce between CPUs, arriving at a cold cache each time.

Modern kernels instead give each CPU its own run queue. A CPU schedules from its own queue without touching anyone else's, so there is no global lock and tasks tend to stay where their cache is warm. The price is that queues can drift out of balance, one CPU overloaded while another idles, so a separate balancing mechanism is required.

  • Common queue: automatic balance, one contended lock
  • Per-CPU queues: no global lock, better cache use
  • Per-CPU queues need explicit load balancing
  • The Linux and Windows schedulers both keep per-CPU queues
Key reference

Terms, operations, and practical uses

Core vocabulary

  • SMPSymmetric multiprocessing: every CPU runs the kernel and schedules itself.
  • Run queueThe list of ready tasks a CPU schedules from; one per CPU in modern kernels.
  • Processor affinityKeeping a task on the CPU whose cache holds its data.
  • MigrationMoving a task from one CPU's queue to another's.

Mechanisms

  • Push migrationA periodic balancer moves tasks off an overloaded CPU.
  • Pull migrationAn idle CPU steals a waiting task from a busy one.
  • Hard affinitysched_setaffinity / taskset: an allowed-CPU set the scheduler must obey.
  • SMTTwo or more hardware threads per core, each seen as a logical CPU.
Implementation

Load balancing across two CPUs

from collections import deque

# name -> (burst, pinned CPU or None). All tasks start on CPU 0's queue.
TASKS = {"T1": (3, None), "T2": (2, None), "T3": (2, 0), "T4": (2, None), "T5": (3, None)}
CPUS = 2


def allowed(name, cpu):
    pin = TASKS[name][1]
    return pin is None or pin == cpu


def take_from_tail(queue, cpu):
    # Migrate the task that would wait longest, skipping pinned tasks.
    for i in range(len(queue) - 1, -1, -1):
        if allowed(queue[i], cpu):
            name = queue[i]
            del queue[i]
            return name
    return None


def simulate():
    queues = [deque(TASKS), deque()]
    running = [None] * CPUS
    left = {name: burst for name, (burst, _) in TASKS.items()}
    log, events, t = [], [], 0
    while any(running) or any(queues):
        for cpu in range(CPUS):
            if running[cpu]:
                continue
            if queues[cpu]:
                running[cpu] = queues[cpu].popleft()
            else:
                busiest = max(range(CPUS), key=lambda k: len(queues[k]))
                running[cpu] = take_from_tail(queues[busiest], cpu)
                if running[cpu]:
                    events.append(f"t={t}: CPU {cpu} pulls {running[cpu]}")
            if running[cpu]:
                log.append((cpu, running[cpu], t, t + left[running[cpu]]))
        # Push migration when the queues differ by two or more.
        long, short = (0, 1) if len(queues[0]) >= len(queues[1]) else (1, 0)
        if len(queues[long]) - len(queues[short]) >= 2:
            name = take_from_tail(queues[long], short)
            if name:
                queues[short].append(name)
                events.append(f"t={t}: push {name} to CPU {short}")
        for cpu in range(CPUS):
            if running[cpu]:
                left[running[cpu]] -= 1
                if left[running[cpu]] == 0:
                    running[cpu] = None
        t += 1
    return log, events


log, events = simulate()
for e in events:
    print(e)
for cpu in range(CPUS):
    runs = [f"{name} {start}-{end}" for c, name, start, end in log if c == cpu]
    print(f"CPU {cpu}: {', '.join(runs)}")
print("Makespan on 2 CPUs:", max(end for *_, end in log))
print("Makespan on 1 CPU:", sum(burst for burst, _ in TASKS.values()))
#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <string>
#include <vector>

struct Task {
    std::string name;
    int burst, pin;  // pin = -1 means the task may run on any CPU
};
struct Run {
    int cpu;
    std::string name;
    int start, end;
};

// All tasks start on CPU 0's queue.
const std::vector<Task> TASKS = {{"T1", 3, -1}, {"T2", 2, -1}, {"T3", 2, 0}, {"T4", 2, -1}, {"T5", 3, -1}};
const int CPUS = 2;

bool allowed(const std::string& name, int cpu) {
    for (const Task& t : TASKS) {
        if (t.name == name) return t.pin == -1 || t.pin == cpu;
    }
    return false;
}

// Migrate the task that would wait longest, skipping pinned tasks.
std::string takeFromTail(std::deque<std::string>& queue, int cpu) {
    for (int i = static_cast<int>(queue.size()) - 1; i >= 0; i--) {
        if (allowed(queue[i], cpu)) {
            std::string name = queue[i];
            queue.erase(queue.begin() + i);
            return name;
        }
    }
    return "";
}

int main() {
    std::vector<std::deque<std::string>> queues(CPUS);
    std::map<std::string, int> left;
    for (const Task& t : TASKS) {
        queues[0].push_back(t.name);
        left[t.name] = t.burst;
    }
    std::vector<std::string> running(CPUS);
    std::vector<Run> log;

    for (int t = 0; !queues[0].empty() || !queues[1].empty() || !running[0].empty() || !running[1].empty(); t++) {
        for (int cpu = 0; cpu < CPUS; cpu++) {
            if (!running[cpu].empty()) continue;
            if (!queues[cpu].empty()) {
                running[cpu] = queues[cpu].front();
                queues[cpu].pop_front();
            } else {
                int busiest = queues[0].size() >= queues[1].size() ? 0 : 1;
                running[cpu] = takeFromTail(queues[busiest], cpu);
                if (!running[cpu].empty()) {
                    std::cout << "t=" << t << ": CPU " << cpu << " pulls " << running[cpu] << '\n';
                }
            }
            if (!running[cpu].empty()) log.push_back({cpu, running[cpu], t, t + left[running[cpu]]});
        }
        // Push migration when the queues differ by two or more.
        int lng = queues[0].size() >= queues[1].size() ? 0 : 1, sht = 1 - lng;
        if (queues[lng].size() >= queues[sht].size() + 2) {
            std::string name = takeFromTail(queues[lng], sht);
            if (!name.empty()) {
                queues[sht].push_back(name);
                std::cout << "t=" << t << ": push " << name << " to CPU " << sht << '\n';
            }
        }
        for (int cpu = 0; cpu < CPUS; cpu++) {
            if (!running[cpu].empty() && --left[running[cpu]] == 0) running[cpu].clear();
        }
    }

    int makespan = 0, total = 0;
    for (int cpu = 0; cpu < CPUS; cpu++) {
        std::cout << "CPU " << cpu << ": ";
        bool first = true;
        for (const Run& r : log) {
            if (r.cpu != cpu) continue;
            std::cout << (first ? "" : ", ") << r.name << ' ' << r.start << '-' << r.end;
            first = false;
            makespan = std::max(makespan, r.end);
        }
        std::cout << '\n';
    }
    for (const Task& t : TASKS) total += t.burst;
    std::cout << "Makespan on 2 CPUs: " << makespan << '\n';
    std::cout << "Makespan on 1 CPU: " << total << '\n';
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main {
    record Task(String name, int burst, int pin) {} // pin = -1 means any CPU

    record Run(int cpu, String name, int start, int end) {}

    // All tasks start on CPU 0's queue.
    static final List<Task> TASKS = List.of(
            new Task("T1", 3, -1), new Task("T2", 2, -1), new Task("T3", 2, 0),
            new Task("T4", 2, -1), new Task("T5", 3, -1));
    static final int CPUS = 2;

    static boolean allowed(String name, int cpu) {
        for (Task t : TASKS) {
            if (t.name().equals(name)) return t.pin() == -1 || t.pin() == cpu;
        }
        return false;
    }

    // Migrate the task that would wait longest, skipping pinned tasks.
    static String takeFromTail(LinkedList<String> queue, int cpu) {
        for (int i = queue.size() - 1; i >= 0; i--) {
            if (allowed(queue.get(i), cpu)) return queue.remove(i);
        }
        return null;
    }

    public static void main(String[] args) {
        List<LinkedList<String>> queues = List.of(new LinkedList<>(), new LinkedList<>());
        Map<String, Integer> left = new HashMap<>();
        for (Task t : TASKS) {
            queues.get(0).add(t.name());
            left.put(t.name(), t.burst());
        }
        String[] running = new String[CPUS];
        List<Run> log = new ArrayList<>();

        for (int t = 0; !queues.get(0).isEmpty() || !queues.get(1).isEmpty() || running[0] != null || running[1] != null; t++) {
            for (int cpu = 0; cpu < CPUS; cpu++) {
                if (running[cpu] != null) continue;
                if (!queues.get(cpu).isEmpty()) {
                    running[cpu] = queues.get(cpu).removeFirst();
                } else {
                    int busiest = queues.get(0).size() >= queues.get(1).size() ? 0 : 1;
                    running[cpu] = takeFromTail(queues.get(busiest), cpu);
                    if (running[cpu] != null) System.out.println("t=" + t + ": CPU " + cpu + " pulls " + running[cpu]);
                }
                if (running[cpu] != null) log.add(new Run(cpu, running[cpu], t, t + left.get(running[cpu])));
            }
            // Push migration when the queues differ by two or more.
            int lng = queues.get(0).size() >= queues.get(1).size() ? 0 : 1, sht = 1 - lng;
            if (queues.get(lng).size() - queues.get(sht).size() >= 2) {
                String name = takeFromTail(queues.get(lng), sht);
                if (name != null) {
                    queues.get(sht).add(name);
                    System.out.println("t=" + t + ": push " + name + " to CPU " + sht);
                }
            }
            for (int cpu = 0; cpu < CPUS; cpu++) {
                if (running[cpu] == null) continue;
                left.merge(running[cpu], -1, Integer::sum);
                if (left.get(running[cpu]) == 0) running[cpu] = null;
            }
        }

        int makespan = 0, total = 0;
        for (int cpu = 0; cpu < CPUS; cpu++) {
            List<String> runs = new ArrayList<>();
            for (Run r : log) {
                if (r.cpu() != cpu) continue;
                runs.add(r.name() + " " + r.start() + "-" + r.end());
                makespan = Math.max(makespan, r.end());
            }
            System.out.println("CPU " + cpu + ": " + String.join(", ", runs));
        }
        for (Task t : TASKS) total += t.burst();
        System.out.println("Makespan on 2 CPUs: " + makespan);
        System.out.println("Makespan on 1 CPU: " + total);
    }
}
Watch it run

Step through it

Running on T1 3, T2 2, T3 2 (pinned to CPU 0), T4 2, T5 3; all start on CPU 0

CPU 0idlenothing to runcache warm for—run queueT1T2T3pinnedT4T5CPU 1idlenothing to runcache warm for—run queueCPU 0CPU 10123456789101112per-CPU run queues: fast, but they can fall out of balance
Step 1

Two CPUs, five tasks, all queued on CPU 0

This is symmetric multiprocessing (SMP): both CPUs schedule themselves, each from its own run queue. A new task usually starts on the CPU of the parent that created it, so all five tasks land in CPU 0's queue. T3 is pinned to CPU 0 with hard affinity. CPU 1 has nothing to do.

Output
1 / 10
4

Processor Affinity

While a task runs, its data fills that CPU's caches. If the task later runs on another CPU, that cache is useless to it: the new CPU must fetch everything from memory again, and the old CPU's copies must be invalidated. Processor affinity is the scheduler's tendency to keep a task on the CPU it last ran on.

Soft affinity is a preference: the scheduler tries to keep the task on the same CPU but will move it if balancing demands. Hard affinity is a rule set by the program or administrator, for example with Linux sched_setaffinity() or taskset: the task may run only on the listed CPUs, even if that leaves others idle. On NUMA machines, where each CPU has its own local memory, affinity matters twice over, because a moved task also ends up far from its memory.

  • Affinity preserves warm caches
  • Soft affinity: a preference the balancer may override
  • Hard affinity: a constraint it must respect
  • NUMA: moving a task also moves it away from its memory
5

Load Balancing: Push and Pull Migration

  1. Measure – compare queue lengths or weighted loads across CPUs.
  2. Push – a periodic pass moves tasks off an overloaded CPU.
  3. Pull – an idle CPU steals a waiting task from a busy one.
  4. Choose carefully – prefer tasks with cold caches, and never move a task outside its hard-affinity set.

With per-CPU queues, load balancing keeps the work spread evenly. It is done in two complementary ways, and real kernels use both.

Push migration is periodic: a balancing routine checks the load on each CPU and moves tasks from overloaded queues to lighter ones. Pull migration is on demand: when a CPU becomes idle it steals a waiting task from a busy CPU's queue. In both cases the best task to move is one that has not run recently, because its cache is already cold.

  • Push: periodic, from the overloaded CPU's point of view
  • Pull: immediate, from the idle CPU's point of view
  • Balancing works against affinity; every move costs cache
6

Multicore Processors and Hardware Threads

A multicore chip puts several cores on one die, and many cores also run two or more hardware threads (Intel Hyper-Threading, called simultaneous multithreading or SMT). While one thread stalls waiting for memory, which can take hundreds of cycles, the core switches to the other thread instead of idling.

The operating system sees each hardware thread as a logical CPU, but they are not equal: two threads on one core share its execution units and caches. Multicore scheduling therefore works at two levels. The OS chooses which software thread runs on each logical CPU, and prefers to spread busy tasks across physical cores before doubling them up on the hardware threads of one core.

  • Hardware threads hide memory stalls on one core
  • Logical CPUs on one core share execution units and cache
  • Spread across cores first, then across hardware threads
  • Heterogeneous chips (big.LITTLE, P-cores and E-cores) add a choice of core type