module always in scope
Channel
A queue between fibres. Channel.send puts a value in without waiting; Channel.recv takes the oldest one out, waiting until there is one. How forks share data.
A Channel<T> carries values of type T from the fibres that send to the fibres that receive. It is how forks share data: two forks that both write one var are refused, because they would interleave and lose a write, and a channel is the way round that.
A channel belongs to the switch that made it. Most programs use one as a mailbox: every producer sends into it, and one loop receives and decides what to do with each value.
Switch.run { sw ->
let ch = Channel.make(sw);
let _ = fork(sw) { -> let _ = Channel.send(ch, 1); let _ = Channel.send(ch, 2); () };
let _ = fork(sw) { -> let _ = Channel.send(ch, 10); () };
Channel.recv(ch) + Channel.recv(ch) + Channel.recv(ch)
}
13
A channel has no clock: recv waits for a value or a close and nothing else. A timer is a fibre that sleeps and then sends.
Functions
func make :: Switch -> Channel<'a> raises HandleRefused
A new, empty channel belonging to the switch sw. When the switch exits, the channel goes with it. Raises HandleRefused if sw has already exited.
Switch.run { sw -> let ch = Channel.make(sw); Channel.send(ch, "hi") }
true
func send :: Channel<'a>, 'a -> Bool
Puts x at the back of the channel and answers true. It never waits and never raises, so a fork body can send without a try; it answers false when the value went nowhere, because the channel is closed or its switch has exited.
Switch.run { sw ->
let ch = Channel.make(sw);
let before = Channel.send(ch, 1);
let _ = Channel.close(ch);
(before, Channel.send(ch, 2))
}
(true, false)
func recv :: Channel<'a> -> 'a raises Err.Closed, HandleRefused
The oldest value in the channel, removed. When the channel is empty it waits, and the other fibres run, until a value is sent or the channel is closed. Raises Closed once the channel is closed and empty, and HandleRefused once its switch has exited. When every fibre is waiting and nothing can send, the program stops with a deadlock that names the channel.
Switch.run { sw ->
let ch = Channel.make(sw);
let _ = fork(sw) { -> let _ = Channel.send(ch, "from a fork"); () };
Channel.recv(ch)
}
from a fork
func close :: Channel<'a> -> () raises HandleRefused
No more values go in; the ones already in still come out. A recv after the last of them raises Closed, and a send answers false.
Switch.run { sw ->
let ch = Channel.make(sw);
let _ = Channel.send(ch, 7);
let _ = Channel.close(ch);
let kept = Channel.recv(ch);
let after = try Channel.recv(ch) rescue Err.Closed(_) => -1 end;
(kept, after)
}
(7, -1)