# 11.2 Task scopes with Tasks and Spawn

> `Tasks` opens a space where tasks that progress together are spawned; `EndTasks` waits for **all** of them to finish, so none is left loose.

Web page: https://pseudolearn.app/en/spec/tareas/ambitos

> **In one sentence**
>
> `Tasks` opens a space where tasks that progress together are spawned; `EndTasks` waits for **all** of them to finish, so none is left loose.

## 11.2.1 How to write it

```pseudolearn
Tasks ⟦«fallo»⟧
  Spawn «Unidad»(«argumentos»);
  Define «asa» As Task<«tipo»> <- Spawn «Unidad»(«argumentos»);
  «instrucciones»
EndTasks
```

> **Parts**
>
> - `Tasks` opens the scope. «failure» is an optional name that, after `EndTasks`, tells whether any task failed.
> - `Spawn` creates a child task that runs a `Suspendible` unit. It is only written directly inside the scope.
> - A **handle** `Task<T>` keeps the spawned task; its only use is `Await handle` to get the result.
> - `EndTasks` joins all children: it waits for those still alive.

## 11.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`.

### Program: Two tasks and their join

```pseudolearn
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";
EndAlgorithm
```

**Output**

```text
lanzadas
Hola, Ana
Hola, Leo
todas terminaron
```

*The program finishes normally.*

**Figure 11.2-1: A task scope**

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.

The parent spawns two children and carries on. At `EndTasks` it waits for both to finish; afterwards none is alive.

A handle gets a child's value back:

### Program: Waiting for results

```pseudolearn
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
EndAlgorithm
```

**Output**

```text
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).

### Program: The first error rules

```pseudolearn
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
EndAlgorithm
```

**Output**

```text
primer error: división entre cero
```

*The program finishes normally.*

> **Limit**
>
> - `Spawn` arguments must be **transferable** and cannot go by reference: tasks share no mutable memory.
> - A handle cannot leave the scope: assigning, passing or returning it is `taskHandleEscape`.
> - A trap in any task ends **the whole** run, without cleanups.

> **Common mistakes**
>
> ### Program: Spawn outside Tasks
>
> ```pseudolearn
> Algorithm Fuera
>   Spawn Saludo();
> EndAlgorithm
>
> Subroutine Suspendable Saludo()
> EndSubroutine
> ```
>
> **Diagnostics**
> - `spawnOutsideTaskScope` (error, 2:3): Spawn is only allowed in the direct lexical body of tasks
>
> *The program finishes with an error.*

> **Under the hood**
>
> `Spawn` reserves a new task in the engine's schedule with its own frame; `EndTasks` is a join instruction that suspends the parent while any child is still alive.
>
> **Intermediate representation**
>
> ```text
> module Orden en
> func suspendible @Saludar(%0: str) -> unit {
> b0() mass 1:
>   stmt.enter @2:3-2:25
>   %1 = const.str "Hola, " @2:9-2:17
>   out.write %1, %0, newline @2:3-2:25
>   stmt.exit @2:3-2:25
>   return @3:1-3:14
> }
> func suspendible @main() -> unit {
> b0() mass 3:
>   %0 = task.scope_open @6:3-10:11
>   stmt.enter @7:5-7:25
>   %1 = const.str "Ana" @7:19-7:24
>   %2 = task.spawn %0, @task:Saludar(%1) @7:5-7:25
>   stmt.exit @7:5-7:25
>   stmt.enter @8:5-8:25
>   %3 = const.str "Leo" @8:19-8:24
>   %4 = task.spawn %0, @task:Saludar(%3) @8:5-8:25
>   stmt.exit @8:5-8:25
>   stmt.enter @9:5-9:21
>   %5 = const.str "lanzadas" @9:11-9:21
>   out.write %5, newline @9:5-9:21
>   stmt.exit @9:5-9:21
>   task.cancel_point b2()
>   task.scope_boundary %0, b3()
>   task.scope_join %0 @6:3-10:11
>   jump b1() @6:3-10:11
> b1() mass 1:
>   stmt.enter @11:3-11:27
>   %6 = const.str "todas terminaron" @11:9-11:27
>   out.write %6, newline @11:3-11:27
>   stmt.exit @11:3-11:27
>   return @12:1-12:13
> b2() mass 0:
>   task.scope_join %0 @6:3-10:11
>   return @6:3-10:11
> b3() mass 0:
>   task.scope_join %0 @6:3-10:11
>   jump b1()
> }
> func suspendible @task:Saludar(%0: str) -> unit {
> b0() mass 0:
>   %1 = call @Saludar(%0) @1:1-1:49
>   task.outcome success @1:1-1:49
>   return @1:1-1:49
> }
> ```

**In short**
- `Tasks` opens a scope and `EndTasks` waits for all its children.
- `Spawn` creates 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.

**See also**
- [11.1 Suspendible units and Await](https://pseudolearn.app/en/spec/tareas/suspendible.md)
- [11.3 Channels and Select](https://pseudolearn.app/en/spec/tareas/canales.md)
- [3.13 immutable and snapshot](https://pseudolearn.app/en/spec/tipos/inmutable.md)
