ENع
→Real-time scheduling
الدرس S1 · Special topics

Real-time scheduling and priority inversion

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة11 خطوة5 أسئلةIntermediate
عن هذا الدرس

A real-time task is only correct if it is also on time. See how rate monotonic scheduling gives each periodic task a priority, how a simple utilisation test (and its EDF cousin) promises every deadline, and how one lock quietly breaks that promise. Step through a 13 ms run on Linux SCHED_FIFO where a high-priority task misses its deadline behind a medium one, then replay it with priority inheritance and watch it finish 6 ms early. This builds on the CPU scheduling module (Round robin and the time slice) and on Locks, spinlocks and atomic instructions; the Embedded lesson Priority inversion and priority inheritance shows the same bug on a microcontroller.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل S1 · تفاعلي
01 / 11

On time, not just fast

A real-time task is late if it finishes after its deadline, even when the answer is right. Each of our three periodic tasks wakes every period, needs some work time (the longest it can ever take), and must finish before its next wake-up.

task         period   work   deadline
H control    10 ms    2 ms   end of its period
M video      20 ms    8 ms   end of its period
L logger     40 ms    3 ms   end of its period

H  steers the machine; needs the bus for 1 ms
M  encodes video; never touches the bus
L  writes a log over the bus for 3 ms

real time = predictable, not fast (Berkeley CS162)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. On time, not just fast

    A real-time task is late if it finishes after its deadline, even when the answer is right. Each of our three periodic tasks wakes every period, needs some work time (the longest it can ever take), and must finish before its next wake-up.

    task         period   work   deadline
    H control    10 ms    2 ms   end of its period
    M video      20 ms    8 ms   end of its period
    L logger     40 ms    3 ms   end of its period
    
    H  steers the machine; needs the bus for 1 ms
    M  encodes video; never touches the bus
    L  writes a log over the bus for 3 ms
    
    real time = predictable, not fast (Berkeley CS162)
  2. Rate monotonic priorities

    Rate monotonic scheduling gives the shortest period the highest priority: H gets 3, M gets 2, L gets 1. In our example they run as Linux SCHED_FIFO threads: the CPU always runs the highest-priority ready thread and preempts lower ones at once.

    rate monotonic: shorter period -> higher priority
      H  period 10 ms  ->  priority 3
      M  period 20 ms  ->  priority 2
      L  period 40 ms  ->  priority 1
    
    Linux SCHED_FIFO (sched(7)):
      priorities 1 (low) to 99 (high)
      a higher-priority thread that becomes ready preempts
      no time slice: a thread runs until it blocks or yields
  3. The utilisation test

    Add up work divided by period: U = 0.675. Liu and Layland proved rate monotonic meets every deadline when U is at most 0.780 for three tasks. EDF, earliest deadline first, can go up to 1. But both assume tasks never wait for each other.

    U = sum of work / period
      H  2 / 10  = 0.200
      M  8 / 20  = 0.400
      L  3 / 40  = 0.075
      total     = 0.675
    
    rate monotonic bound  n(2^(1/n) - 1), n = 3  = 0.780
      0.675 <= 0.780  -> every deadline met (a sufficient test)
      as n grows the bound falls toward ln 2 = 0.693
    
    EDF (run the nearest deadline first)
      every deadline met if and only if U <= 1
      Linux SCHED_DEADLINE is EDF plus a bandwidth server (CBS)
    
    both tests assume independent tasks: no locks
  4. L takes the bus lock

    Now add a lock. At 0 ms only L is awake. It locks the bus mutex and starts its 3 ms of bus work. Our mutex is a plain one, with no priority tricks.

    the bus code, run by H and L:
      1  pthread_mutex_lock(&bus);
      2  use_bus();
      3  pthread_mutex_unlock(&bus);
    
    t = 0 ms   L awake, nothing else is
               L: pthread_mutex_lock(&bus)  -> owner L
               mutex protocol PTHREAD_PRIO_NONE (the default)
  5. H wakes and preempts

    At 1 ms H wakes up. It outranks L, so the CPU switches to H at once. L is paused in the middle of its bus work and still owns the lock.

    t = 1 ms   H wakes (priority 3 > 1)  -> preempts L
               H runs 1 ms of plain work
               L is ready but paused, still the owner
               H deadline = 1 + 10 = 11 ms
  6. H blocks on the lock

    At 2 ms H needs the bus and calls lock, but L owns it. H must sleep until L unlocks. That is fine so far: L only has 2 ms of bus work left.

    t = 2 ms   H: pthread_mutex_lock(&bus)  -> owned by L
               H blocks (sleeps, uses no CPU)
               L is the highest ready thread: L runs
               L bus work left: 2 ms, then 1 ms
    
    a high task waiting for a low one is expected here:
    the wait is as long as L's critical section
    (critical section = the code run while holding the lock)
  7. M runs ahead of H

    At 3 ms M wakes. It needs no lock, and it outranks L, so it preempts L and runs for 8 ms. H waits on L, and L waits on M: the highest-priority task is stuck behind a medium one. This is priority inversion.

    t = 3 ms   M wakes (priority 2 > L's 1)  -> preempts L
    t = 3..11 M runs 8 ms
               H blocked on the lock, L ready but outranked
    
    unbounded: H now waits as long as ANY medium task
    runs, not just for L's short critical section
    
    timeline so far   LHLMMMMMMMM
  8. H misses its deadline

    M finishes at 11 ms. L does its last 1 ms of bus work and unlocks at 12 ms, which wakes H. H finishes at 13 ms, 2 ms after its deadline. The utilisation test said it was safe.

    t = 11  L runs its last bus millisecond
    t = 12  L: pthread_mutex_unlock(&bus)  -> H wakes, owner H
    t = 12  H runs 1 ms on the bus
    t = 13  H done      deadline 11   late by 2 ms
    
    plain mutex   LHLMMMMMMMMLH
    H blocked from 2 to 12 ms: 10 ms
  9. L inherits H's priority

    Same run, with priority inheritance. At 2 ms H blocks on the lock, and the kernel lends its priority 3 to L, the owner. At 3 ms M wakes but cannot preempt L now. L finishes its bus work.

    mutex protocol PTHREAD_PRIO_INHERIT
      the owner runs at the higher of its own priority
      and the priority of its highest waiter
    
    t = 0   L locks the bus
    t = 1   H wakes and preempts L
    t = 2   H blocks on the lock  -> L runs at priority 3
    t = 3   M wakes: 2 < 3, M waits
    t = 4   L unlocks  -> back to priority 1; H owns the lock
  10. H finishes on time

    L unlocks at 4 ms and drops back to priority 1. H gets the lock and finishes at 5 ms, 6 ms early. M runs afterwards. H now waits at most one critical section of L, never for M.

    t = 4   H owns the lock, runs 1 ms
    t = 5   H done    deadline 11   6 ms to spare
    t = 5..13 M runs 8 ms, done at 13
    
    plain mutex   LHLMMMMMMMMLH   H done at 13
    inheritance   LHLLHMMMMMMMM   H done at 5
    H blocked: 10 ms -> 2 ms (bounded by L's 3 ms critical section)
    
    the same scheduler as a Python simulation:
    
    # name: (priority, release ms, [(needs_lock, ms), ...])
    TASKS = {"H": (3, 1, [(False, 1), (True, 1)]),
             "M": (2, 3, [(False, 8)]),
             "L": (1, 0, [(True, 3)])}
    
    def run(inherit):
        work = {n: [list(s) for s in w] for n, (p, r, w) in TASKS.items()}
        holder, waiting, done, out, t = None, set(), {}, "", 0
        def prio(n):
            p = TASKS[n][0]
            if inherit and n == holder and waiting:
                p = max([p] + [TASKS[w][0] for w in waiting])
            return p
        while len(done) < len(TASKS):
            ready = [n for n in TASKS if TASKS[n][1] <= t
                     and n not in done and n not in waiting]
            n = max(ready, key=prio)
            seg = work[n][0]
            if seg[0] and holder not in (None, n):
                waiting.add(n)             # blocked on the lock
                continue
            if seg[0]:
                holder = n
            out += n
            seg[1] -= 1
            t += 1
            if seg[1] == 0:
                work[n].pop(0)
                if seg[0] and not (work[n] and work[n][0][0]):
                    holder, waiting = None, set()   # unlock wakes waiters
                if not work[n]:
                    done[n] = t
        return out, done["H"]
    
    for inherit in (False, True):
        order, h = run(inherit)
        print("inherit" if inherit else "plain  ", order, "H done at", h)
    
    prints:
    plain   LHLMMMMMMMMLH H done at 13
    inherit LHLLHMMMMMMMM H done at 5
  11. Turning it on

    On Linux a program asks for this when it makes the mutex: PTHREAD_PRIO_INHERIT. The kernel then boosts the owner while a higher thread waits. Mars Pathfinder kept resetting in 1997 until engineers switched on the same kind of option in its VxWorks mutex.

    C99, POSIX threads (cc -std=c99 -pthread):
    
    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <stdio.h>
    
    int main(void) {
        pthread_mutexattr_t attr;
        pthread_mutex_t bus;
        int proto = PTHREAD_PRIO_NONE;
    
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
        pthread_mutex_init(&bus, &attr);
        pthread_mutexattr_getprotocol(&attr, &proto);
    
        pthread_mutex_lock(&bus);   /* while held, the owner runs at the */
        pthread_mutex_unlock(&bus); /* priority of its highest waiter    */
    
        puts(proto == PTHREAD_PRIO_INHERIT ? "inheritance on" : "off");
        pthread_mutex_destroy(&bus);
        pthread_mutexattr_destroy(&attr);
        return 0;
    }
    
    prints:  inheritance on
    
    threads become SCHED_FIFO with pthread_setschedparam()
    (needs privilege, else EPERM); in the kernel, rt-mutexes
    and PI-futexes do the boosting.

اختبار يتاح بعد الخطوة الأخيرة.