11.2.1 How to write it
Tasks ⟦«fallo»⟧
Spawn «Unidad»(«argumentos»);
Define «asa» As Task<«tipo»> <- Spawn «Unidad»(«argumentos»);
«instrucciones»
EndTasks11.2.2 How it works
Spawn does not stop the parent: it creates the child and the parent goes on with the next statement. The children run when the parent pauses, at the latest at EndTasks.
ProgramTwo tasks and their join
Subroutine Suspendable Saludar(nombre As String)
Write "Hola, ", nombre;
EndSubroutine
Algorithm Orden
Tasks
Spawn Saludar("Ana");
Spawn Saludar("Leo");
Write "lanzadas";
EndTasks
Write "todas terminaron";
EndAlgorithmOutput
lanzadas Hola, Ana Hola, Leo todas terminaron
The program finishes normally.
EndTasks it waits for both to finish; afterwards none is alive.The parent's line runs from top to bottom. At Tasks it spawns two children, Ana and Leo, that progress in parallel. Both join the parent again at EndTasks.
A handle gets a child's value back:
ProgramWaiting for results
Subroutine Suspendable Cuadrado(n As Integer) As Integer
Return n * n;
EndSubroutine
Algorithm Paralelo
Tasks
Define a As Task<Integer> <- Spawn Cuadrado(3);
Define b As Task<Integer> <- Spawn Cuadrado(4);
Write Await a + Await b;
EndTasks
EndAlgorithmOutput
25
The program finishes normally.
11.2.3 Failures
If the children return Result<T, E>, the first Error to finish cancels the others and jumps to EndTasks. The scope's failure name is an Optional<TaskFailure<E>>: it is Nothing if all went well, or Something with a TaskFailure whose fields are f.first (the first error), f.associated (the errors that arrived later) and f.cancelled (how many children were cancelled).
ProgramThe first error rules
Subroutine Suspendable Dividir(a As Integer, b As Integer) As Result<Integer, String>
If b = 0 Then
Return Failure("división entre cero");
EndIf
Return Success(a Div b);
EndSubroutine
Algorithm Fallos
Tasks fallo
Spawn Dividir(10, 2);
Spawn Dividir(1, 0);
EndTasks
Switch fallo Do
Some(f):
Write "primer error: ", f.first;
None:
Write "todo bien";
EndSwitch
EndAlgorithmOutput
primer error: división entre cero
The program finishes normally.
In short
Tasksopens a scope andEndTaskswaits for all its children.Spawncreates a child without stopping the parent.- A handle is only used with
Await. - The first error cancels the siblings and is kept in the failure name.