Skip to content

Channel

Channels provide a safe way for concurrent tasks to communicate by sending and receiving values. They are the primary synchronization mechanism in Chuks, similar to Go channels.

import { channel } from "std/channel";

Creates a new channel. The buffer size controls how many values can be queued before a send blocks.

import { channel } from "std/channel";
// Unbuffered channel — send blocks until a receiver is ready
const ch = channel.new(0);
// Buffered channel — can hold up to 5 values before blocking
const buffered = channel.new(5);

Sends a value into the channel. Blocks if the channel buffer is full (or unbuffered and no receiver is ready).

channel.send(ch, "hello");
channel.send(ch, 42);

Receives a value from the channel. Blocks if no value is available. Returns null if the channel is closed and empty.

const msg = channel.receive(ch);
println(msg); // "hello"

Closes the channel. No more values can be sent after closing. Receivers will get remaining buffered values, then null.

channel.close(ch);

channel.tryReceive(ch): { value: any, ok: bool }

Section titled “channel.tryReceive(ch): { value: any, ok: bool }”

Attempts to receive a value without blocking. Returns a map with value and ok:

  • ok: true — a value was received
  • ok: false — channel was empty (would have blocked)
const result = channel.tryReceive(ch);
if (result["ok"]) {
println("Got:", result["value"]);
} else {
println("Channel empty");
}

Attempts to send a value without blocking. Returns true if the value was sent, false if the channel buffer is full.

const sent = channel.trySend(ch, "data");
if (!sent) {
println("Channel full, dropping message");
}
import { channel } from "std/channel";
function main() {
const ch = channel.new(0);
// Producer task
spawn {
for (var i = 0; i < 5; i = i + 1) {
channel.send(ch, i);
}
channel.close(ch);
}
// Consumer — receive until channel is closed
var val = channel.receive(ch);
while (val != null) {
println(val);
val = channel.receive(ch);
}
println("Done");
}

Output:

0
1
2
3
4
Done
FunctionDescription
channel.new(bufferSize)Create a new channel with the given buffer size
channel.send(ch, value)Send a value (blocks if full)
channel.receive(ch)Receive a value (blocks if empty)
channel.close(ch)Close the channel
channel.tryReceive(ch)Non-blocking receive → { value, ok }
channel.trySend(ch, value)Non-blocking send → bool