Skip to content

SpecificationXIII · The engine inside

13.3

The task schedule

Tasks do not really run at the same time: a deterministic schedule decides which one advances, and that is why every run always follows the same order.

Markdown version

13.3.1 How it works

Only one task runs at any moment. The others are ready (in a queue), suspended (waiting for something) or finished.

  • The root task has identity 0; every Spawn assigns the next one: 1, 2, 3…
  • The ready queue is FIFO: new tasks, woken tasks and tasks that yield go to the back.
  • When the current task suspends or ends, the head of the queue resumes. Spawn does not displace the parent.
  • So that none hogs the turn, a task that runs 1024 statements in a row inside a suspendible loop yields its place.
Figure 13.3-1.The schedule with the running task, the ready queue and the suspended ones. When the current one suspends, the head of the queue comes in.

On the left, the running task. On the right, the ready queue with tasks 1 and 2, from which the next one to come in leaves. Below, the suspended tasks, where the current one goes if it waits for something.

ProgramThe order of turns

Subroutine Suspendable Contar(nombre As String, canal As Channel<Integer>)
  For i <- 1 To 2 Do
    Write nombre, " ", i;
    If Not Await canal.send(i) Then
      Return;
    EndIf
  EndFor
EndSubroutine

Algorithm Turnos
  Define canal As Channel<Integer> <- channel(4);
  Tasks
    Spawn Contar("A", canal);
    Spawn Contar("B", canal);
    Write "padre";
  EndTasks
EndAlgorithm

Output

padre
A 1
A 2
B 1
B 2

The program finishes normally.

The parent writes first because Spawn does not stop it. At EndTasks it suspends and A, the head of the queue, comes in. Since the channel has room, send does not suspend A, which finishes before B comes in.

13.3.2 Deadlock

If no task is ready and no pending effect can wake any of them, the run ends with taskDeadlock:

ProgramWaiting for something that never comes

Subroutine Suspendable Esperar(canal As Channel<Integer>)
  Switch Await canal.receive() Do
    Some(valor): Write valor;
    None: Write "cerrado";
  EndSwitch
EndSubroutine

Algorithm Bloqueo
  Define canal As Channel<Integer> <- channel(1);
  Tasks
    Spawn Esperar(canal);
  EndTasks
EndAlgorithm

Diagnostics

  • taskDeadlock · error · 2:16 · The task agenda has no runnable tasks or pending effects that can resume it

The program finishes with an error.

In short

  • A single task advances; the others wait in a FIFO queue.
  • Task identities grow from 0 and are never reused.
  • With no ready tasks and no pending effects, the run ends with taskDeadlock.