Simvik

Priority inversion, tick by tick

Simulate a preemptive scheduler with a shared mutex, and see what priority inheritance changes. A hard embedded C problem (RTOS scheduling), run and graded…

hard · RTOS scheduling · rtos · scheduling · mutex · priority-inversion · simulation

Write simulate(t, n, inherit, ticks, out): run n tasks on one CPU for ticks ticks under fixed-priority preemptive scheduling, with one mutex, and write the letter of the task that ran in each tick to out (. if none), then a terminating '\0'.

First reset each task's state: pc 0, eff = prio, not blocked, done if it has no steps. Then for each tick:

  1. Pick the task with the highest eff among those released (release <= tick), not done and not blocked. On a tie, the lowest index. If there is none, the tick is idle.
  2. Look at its next step:
  3. L: if another task owns the mutex, this task becomes blocked. With inherit, the owner's eff is raised to this task's eff if it is lower. Go back to 1 and pick again in the same tick. Otherwise this task becomes the owner, moves to the next step, and you go back to 1.
  4. U: release the mutex, set this task's eff back to its prio, unblock every blocked task (each tries its L again when it next runs), move to the next step, go back to 1.
  5. c: the task runs for this tick. Move to the next step, and the tick is over.

After any step, a task with no steps left is done.

Starter code

void simulate(task_t *t, int n, bool inherit, int ticks, char *out) {
  for (int i = 0; i < n; i++) { t[i].pc = 0; t[i].eff = t[i].prio; t[i].blocked = false; t[i].done = false; }
  for (int now = 0; now < ticks; now++) {
    out[now] = '.';
    int run = -1;
    for (int i = 0; i < n; i++)
      if (!t[i].done && t[i].release <= now && (run < 0 || t[i].prio > t[run].prio)) run = i;
    if (run < 0) continue;
    task_t *k = &t[run];
    while (k->steps[k->pc] == 'L' || k->steps[k->pc] == 'U') k->pc++;   // the mutex is ignored
    out[now] = k->name;
    k->pc++;
    if (k->steps[k->pc] == '\0') k->done = true;
  }
  out[ticks] = '\0';
}

Example tests

The classic inversion

task_t t[] = {
  { 'L', 1, 0, "cLcccUc" },
  { 'M', 2, 3, "ccccc" },
  { 'H', 3, 2, "cLcUc" },
};
show(t, 3, 13);

Expected output:

plain:   LLHMMMMMLLHHL
inherit: LLHLLHHMMMMML

Learn it first

More RTOS scheduling problems