Skip to content

SpecificationXI · Concurrency and asynchrony

11.3

Channels and Select

A channel is a fixed-capacity queue through which some tasks send values and others receive them, in order and without sharing memory.

Markdown version

11.3.1 How it works

Channel<T> is the type and Channel(n) creates one with capacity n. Three operations:

OperationWhat 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
Figure 11.3-1.A channel of capacity 2. The producer waits when it is full; the consumer, when it is empty. Values come out in the order they went in.

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
EndAlgorithm

Output

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
EndAlgorithm

Output

avisos: aviso urgente

The program finishes normally.

In short

  • A channel is a bounded queue between tasks.
  • send and receive are used with Await; close, without it.
  • Select serves the first ready channel, ties broken by written order.