11.3.1 How it works
Channel<T> is the type and Channel(n) creates one with capacity n. Three operations:
| Operation | What it does |
|---|---|
Await c.send(v) | queues v; if full, it waits. Returns False if the channel is closed |
Await c.receive() | takes the first one as Something(v); if empty, it waits. Closed and empty gives Nothing |
c.close() | closes the channel without losing what is queued |
A producer on the left sends values into a channel with two slots holding 20 and 10; a consumer on the right receives them in order.
ProgramA producer and a consumer
Subroutine Suspendable Productor(canal As Channel<Integer>)
For i <- 1 To 3 Do
If Not Await canal.send(i * 10) Then
Break;
EndIf
EndFor
canal.close();
EndSubroutine
Algorithm Tuberia
Define canal As Channel<Integer> <- channel(2);
Tasks
Spawn Productor(canal);
Define seguir As Boolean <- True;
While seguir Do
Switch Await canal.receive() Do
Some(valor):
Write "recibido ", valor;
None:
seguir <- False;
EndSwitch
EndWhile
EndTasks
EndAlgorithmOutput
recibido 10 recibido 20 recibido 30
The program finishes normally.
11.3.2 Select
Select waits on several channels at once and serves the first one that has something. If several are ready, the first written branch wins: the result is always the same.
ProgramServing whichever arrives first
Subroutine Suspendable Avisar(canal As Channel<String>)
If Await canal.send("aviso urgente") Then
canal.close();
EndIf
EndSubroutine
Subroutine Anunciar(origen As String, mensaje As Optional<String>)
Switch mensaje Do
Some(texto): Write origen, ": ", texto;
None: Write origen, ": cerrado";
EndSwitch
EndSubroutine
Algorithm Elige
Define noticias As Channel<String> <- channel(1);
Define avisos As Channel<String> <- channel(1);
Tasks
Spawn Avisar(avisos);
Select
Receive n From noticias:
Anunciar("noticias", n);
Receive a From avisos:
Anunciar("avisos", a);
EndSelect
EndTasks
EndAlgorithmOutput
avisos: aviso urgente
The program finishes normally.
In short
- A channel is a bounded queue between tasks.
sendandreceiveare used withAwait;close, without it.Selectserves the first ready channel, ties broken by written order.