ENع
←Many-core scheduling
Lesson 17 · CPU scheduling

Scheduling on many cores

14 min11 steps5 questionsIntermediate
About this lesson

With one core the scheduler only asks who runs next and for how long. With several cores it must also choose where. Watch jobs on a two-core machine: first sharing one queue, where every pick waits for a lock and every job keeps landing on a core whose cache has forgotten it, then with a queue per core, where caches stay warm until the queues fall out of balance and an idle core steals work. The Hardware lesson on multicore processors explains why each core's cache matters; here we see what the scheduler does about it, and how Linux does it.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 17 · Interactive
01 / 11

Two cores, two caches

A multicore chip has several cores. Each core is a CPU that runs one job at a time. Here there are two. Each has its own small, fast cache, and both share one big, slow main memory.

core      runs one job at a time
cache     small and fast, one per core
memory    big and slow, shared by every core

a value already in the cache: a few nanoseconds
a value fetched from memory:  tens to hundreds of ns
(OSTEP ch. 10)

new question for the scheduler: not only who runs
next and for how long, but also on WHICH core
Loading figure…
or ← →
Read the lesson step by step
  1. Two cores, two caches

    A multicore chip has several cores. Each core is a CPU that runs one job at a time. Here there are two. Each has its own small, fast cache, and both share one big, slow main memory.

    core      runs one job at a time
    cache     small and fast, one per core
    memory    big and slow, shared by every core
    
    a value already in the cache: a few nanoseconds
    a value fetched from memory:  tens to hundreds of ns
    (OSTEP ch. 10)
    
    new question for the scheduler: not only who runs
    next and for how long, but also on WHICH core
  2. One shared queue

    The simplest plan: one queue for all cores, single-queue scheduling (SQMS). Jobs A, B and C wait in it. Each free core takes the front job, A to core 0, B to core 1, and loads its data. The counter tallies slices and reloads.

    SQMS: single-queue multiprocessor scheduling
    
    queue    A  B  C
    core 0   takes A        cache 0: (empty) -> load A
    core 1   takes B        cache 1: (empty) -> load B
    queue    C
    
    any one-core policy works unchanged:
    with 2 cores it just picks the best 2 jobs
  3. Taking turns at the lock

    After one time slice, A and B go to the back of the queue. Both cores want the queue at once, so it has a lock. Core 0 takes the lock first and gets C; core 1 waits, then gets A.

    end of slice 1   queue  C  A  B
    core 0           lock, take C, unlock
    core 1           waits for the lock ... take A
    
    without the lock both cores could take C at once
    more cores = more waiting at the one lock:
    "the system spends more and more time in lock
     overhead" (OSTEP). SQMS does not scale well.
  4. Jobs bounce between cores

    A ran on core 0 but now runs on core 1, whose cache lacks A's data, so it reloads. Every job that runs again lands on the other core and reloads. Running again where its data is warm, called cache affinity, is lost.

    slice   core 0   core 1
    1       A        B        all cold (first run)
    2       C        A        C new, A moved: reload
    3       B        C        B moved, C moved: reload
    
    after 3 slices: 6 reloads in 6 runs
    
    cache affinity: run a job where its data still is
  5. A queue per core

    Start again with one queue per core: multi-queue scheduling (MQMS). Four jobs arrive, and each goes into one queue: A and C to core 0, B and D to core 1. Each core picks from its own queue, so no shared lock.

    MQMS: multi-queue multiprocessor scheduling
    
    a new job goes into exactly ONE queue
    (random, or the one with fewer jobs)
    
    queue 0   A  C        work left: A 4, C 2 slices
    queue 1   B  D        work left: B 6, D 6 slices
    
    each core runs round robin on its own queue
  6. Caches stay warm

    Each core runs round robin on its own queue: A, C, A, C on core 0 and B, D, B, D on core 1. Each job loads its data once, then finds it still in its core's cache while it stays there.

    slice   core 0   core 1
    1       A load   B load
    2       C load   D load
    3       A warm   B warm
    4       C warm   D warm      C is done
    
    4 reloads in 8 runs; no more while no job changes core
    more cores = more queues: no single lock to wait for
  7. Load imbalance

    C finished after slice 4. Now core 0 has only A, while B and D still share core 1. A gets a whole core, twice as much CPU as B or D. Each queue only sees its own jobs.

    slice   core 0   core 1
    5       A        B
    6       A        D           A is done
    
    share of a core, slices 5-6:  A 1   B 0.5   D 0.5
    A gets twice as much CPU as B or D
  8. An idle core

    A finished after slice 6. Core 0's queue is empty, so core 0 sits idle while B and D still take turns on core 1. Half the machine does nothing while work waits.

    slice 7 begins
    queue 0   (empty)     core 0 idle
    queue 1   B  D        core 1 runs B, D waits
    
    left alone, the last job ends after slice 12
  9. Work stealing

    Core 0 peeks at queue 1, sees two jobs against its none, and steals D: a migration. D reloads its data once on core 0, then runs warm. All the work is done after slice 9, not 12.

    work stealing: an empty (or short) queue peeks at
    a fuller one and takes a job from it
    
    slice   core 0   core 1
    7       D load   B
    8       D warm   B
    9       D warm   B           both done
    
    all done after 9 slices (12 without stealing)
    peek too often: overhead; too rarely: imbalance
  10. How Linux does it

    Linux keeps a run queue for every CPU. On a regular tick each CPU checks the balance and pulls tasks from the busiest one. A program can also pin a thread to chosen cores with sched_setaffinity().

    per-CPU run queues: O(1), CFS (2.6.23), EEVDF (6.6)
    balancing: sched_tick() -> sched_balance_rq():
      find the busiest group, its busiest run queue,
      lock both, move tasks to this CPU
    levels: hyperthreads, then cores, then NUMA nodes
    
    pin this thread to core 0 (Linux, C99):
    
    #define _GNU_SOURCE
    #include <sched.h>
    #include <stdio.h>
    
    int main(void) {
        cpu_set_t set;
        CPU_ZERO(&set);
        CPU_SET(0, &set);                       /* core 0 only */
        if (sched_setaffinity(0, sizeof set, &set) == -1) {
            perror("sched_setaffinity");
            return 1;
        }
        printf("running on core %d\n", sched_getcpu());
        return 0;
    }
    
    prints: running on core 0
  11. Balance against affinity

    One shared queue balances load but needs a lock and loses cache affinity. A queue per core scales and keeps caches warm, but drifts out of balance, so it moves jobs now and then, not too often.

    both plans as a Python simulation:
    
    CAP = 2                          # jobs each cache can hold
    def run_on(cache, job):          # True if the data must reload
        miss = job not in cache
        if not miss: cache.remove(job)
        cache.append(job)
        if len(cache) > CAP: cache.pop(0)   # forget the oldest
        return miss
    
    def sqms(jobs, slices):          # one shared queue
        queue, caches, runs, reloads = list(jobs), [[], []], 0, 0
        for t in range(slices):
            picked = [queue.pop(0) for core in (0, 1)]   # under the lock
            for core, job in enumerate(picked):
                runs += 1; reloads += run_on(caches[core], job)
            queue += picked          # back to the end of the queue
        return runs, reloads
    
    def mqms(queues, left, steal):   # one queue per core
        caches, runs, reloads, t = [[], []], 0, 0, 0
        while any(queues):
            t += 1
            for core in (0, 1):
                other = queues[1 - core]
                if steal and not queues[core] and len(other) >= 2:
                    queues[core].append(other.pop())   # steal
            for core in (0, 1):
                if not queues[core]: continue
                job = queues[core].pop(0)
                runs += 1; reloads += run_on(caches[core], job)
                left[job] -= 1
                if left[job]: queues[core].append(job)
        return runs, reloads, t
    
    work = lambda: dict(A=4, B=6, C=2, D=6)
    print("one queue (runs, reloads):", sqms("ABC", 6))
    print("per core (runs, reloads, slices):", mqms([["A", "C"], ["B", "D"]], work(), True))
    print("no stealing:", mqms([["A", "C"], ["B", "D"]], work(), False))
    
    prints:
    one queue (runs, reloads): (12, 12)
    per core (runs, reloads, slices): (18, 5, 9)
    no stealing: (18, 4, 12)

Quiz Unlocks after the last step.