channel - CSP channels between goroutines
The channel library provides CSP-style channels: typed conduits that carry values between a spawned body and the rest of the program (or between several spawns). Where task observes a single result, a channel streams many values and lets producers and consumers rendez-vous.
use channel;
use task;
def ch as channel of int init channel.make(0); # unbuffered
def producer as task of int init spawn {
def i as int init 0;
while ($i < 5) {
channel.send($ch, $i * 10);
$i = $i + 1;
}
channel.close($ch);
return 0;
};
# consumer: drain until the producer closes the channel
def sum as int init 0;
def open as bool init true;
while ($open) {
try {
$sum = $sum + channel.recv($ch);
} catch (e) {
if ($e.kind != "closed") {
throw $e;
}
$open = false;
}
}
task.wait($producer);Why channels (not locks)
A channel is a shared handle: copies, including the deep copy a spawn makes of its captured scope, refer to the one underlying conduit, which is what lets a spawn body and its parent talk. But the values sent through it are copied at the send site, so Jennifer's no-shared-mutable-state guarantee still holds. A mutex or atomic would expose shared mutable state, so locks stay rejected: a channel shares the conduit, never the data.
channel is a contextual keyword: channel of T is a type, but channel stays an ordinary identifier everywhere else (a field or parameter named channel keeps working).
Surface
| Call | Returns | Notes |
|---|---|---|
channel.make(capacity) | channel of T | A new channel. capacity 0 is unbuffered (send blocks for a receiver); n buffers up to n values (above 4,194,304, or 262,144 on jennifer-tiny, is a catchable error of kind "limit"). T comes from the binding. |
channel.send(ch, value) | null | Checks value against the channel's T, deep-copies it in, then sends (blocking per capacity). Wrong type is a catchable error; a send on a closed channel is Error{kind: "closed"}. |
channel.recv(ch) | T | Blocks and returns the next value. On a closed and drained channel it throws a catchable Error{kind: "closed"} ("receive on a closed channel"). |
channel.recvTimeout(ch, ms) | T | recv waiting at most ms milliseconds: the next value, or a catchable Error{kind: "timeout"}. A timeout takes nothing (a value sent later stays for the next receive); 0 polls. Closed and drained throws as recv; task.cancel wakes it. |
channel.close(ch) | null | Closes the channel so a draining receiver sees the end. A second close does nothing. |
channel.select(chs) | T | Fan-in: the next value from any of the channels; drops closed ones and throws Error{kind: "closed"} when all are closed and drained. |
channel.selectTimeout(chs, ms) | T | select waiting at most ms milliseconds: the next value, or a catchable Error{kind: "timeout"}. A timeout takes nothing; 0 polls. All closed and drained throws as select; task.cancel wakes it. |
channel.len(ch) | int | Number of values currently buffered. |
channel.capacity(ch) | int | The channel's buffer capacity (0 = unbuffered). |
Value semantics
channel.send copies the value in, so a later mutation by the sender never reaches the receiver:
def ch as channel of list of int init channel.make(1);
def xs as list of int init [1, 2, 3];
channel.send($ch, $xs);
$xs[0] = 999; # mutate after send
def got as list of int init channel.recv($ch); # still [1, 2, 3]The element type is enforced at both ends. channel.send validates the value against the channel's declared T at the send site (channel.send($intCh, "x") is a catchable "value must be int, got string"), and the receiving binding checks it again (def n as int init channel.recv($ch); rejects a non-int), so a mismatch is caught where it happens, and a channel of int still cannot be assigned to a channel of string. A channel not yet bound to a channel of T (a bare channel.make result) carries no recorded type, so its first send is unchecked (like a fresh generic list literal) until a typed binding stamps T.
Closing and draining
channel.close signals "no more values". A receiver draining with channel.recv sees a catchable Error{kind: "closed"} ("receive on a closed channel") once the buffer is empty, so the idiomatic consumer loop catches that kind and passes anything else on:
def open as bool init true;
while ($open) {
try {
process(channel.recv($ch));
} catch (e) {
if ($e.kind != "closed") {
throw $e; # a failure in process(), not the end of the stream
}
$open = false; # channel drained and closed - done
}
}Only the producer should close, and only once. After close, buffered values still receive until drained; further sends are catchable errors.
select (fan-in)
channel.select(chs) blocks until any channel in the list has a value and returns it - a merge of several producers into one consumer. A closed channel drops out of the wait set; when every channel is closed and drained, select throws a catchable Error{kind: "closed"} ("all channels are closed").
def open as bool init true;
while ($open) {
try {
handle(channel.select([$a, $b, $c]));
} catch (e) {
if ($e.kind != "closed") {
throw $e;
}
$open = false; # every input closed
}
}channel.selectTimeout(chs, ms) bounds the wait: "timeout" when no channel has a value within ms (0 polls), with nothing taken.
select returns the received value, not an index of which channel fired (a channel receive is destructive and Jennifer has no multiple-return, so an index-plus-value form would need a different shape). It is the merge / fan-in primitive, with no per-channel dispatch.
Blocking and cancellation
Channel operations block like Go's: an unbuffered send waits for a receiver, a recv waits for a value. A channel with no counterpart (an unbuffered send nothing will receive, a recv on a channel nothing will send to or close) hangs the program, the same sharp edge as a non-terminating spawn; recvTimeout / selectTimeout bound the wait instead. It does not trigger Go's "all goroutines asleep" deadlock abort: the interpreter keeps a signal-handler goroutine alive (for SIGUSR1 diagnostics), so the runtime never sees every goroutine blocked, and the program waits until it is killed rather than aborting. A spawn body blocked in channel.send / recv / select (or a timeout form) wakes on task.cancel: the call raises "task cancelled". channel.close also unblocks waiters: a parked send raises "send on a closed channel", a drained recv raises "receive on a closed channel" (both kind "closed").
Patterns
| Pattern | Shape |
|---|---|
| Producer / consumer | One spawn sends, the main goroutine drains until close (the opening example). |
| Receive with a deadline | channel.recvTimeout($ch, 500) in a try, with catch (e) { if ($e.kind != "timeout") { throw $e; } ... } for the idle case. No need to spawn a recv task, task.waitTimeout, then task.cancel + task.wait to rescue a value that raced the cancel. |
| Fan-out (worker pool) | Several spawned workers recv from one job channel; closing it signals shutdown, and each worker's recv then ends. |
| Fan-in | Several spawned producers send into one channel (or channel.select over several channels) that one consumer drains; channel.selectTimeout for one with a deadline. |
| Pipeline | Stage N reads its input channel and sends into stage N+1's; each stage closes its output when its input drains. |
Errors
| Kind | Thrown by | When |
|---|---|---|
"closed" | send, recv, recvTimeout, select, selectTimeout | A send on a closed channel; a receive from a closed, drained channel (every channel, for the select forms). |
"timeout" | recvTimeout, selectTimeout | No value within ms; nothing is taken. |
"cancelled" | every blocking call | task.cancel of the spawn blocked in it. |
"limit" | make | A capacity above the cap. |
"runtime" | every call | A wrong argument or element type, an empty list for the select forms, ms negative or above 9,223,372,036,854 (the largest a duration holds). |
See also
task- observe a single spawned result; cancellation and timeouts.- Concurrency - the
spawnmodel and value-semantics capture.
Academy talks
| Talk | What it shows |
|---|---|
| Advanced programming with Jennifer | streaming values between tasks over channels |