Skip to content

std.chan - ZZ

Unbounded lock-free channels for task communication. Green-thread safe by construction: send pushes, recv blocks, try_recv polls. Channels are the primary way tasks exchange data without shared mutable state.

import std.chan

std.chan creates unbounded (lock-free ring + spill — bursts never block the sender) channels. send pushes, recv blocks, try_recv polls. Use channels to pass data between tasks — no shared mutable state, no data races by construction.

import std.chan
c := chan()
chan.send(c, 42)
v: int = chan.recv(c) // blocks
opt: Option<int> = chan.try_recv(c) // .some(v) or .none, never blocks
import std.task
import std.chan
jobs := chan()
out := chan()
for i in 0..4 {
task.spawn(|_| {
while true {
match chan.try_recv(jobs) {
.some(j) => chan.send(out, j * 2),
.none => break,
}
}
})
}
for i in 0..100 { chan.send(jobs, i) }
// Drain `out` with recv/try_recv
  • Unbounded — a fast producer can outpace a slow consumer; memory grows. Apply backpressure externally if needed.
  • recv blocks the task (not the OS thread) — other tasks keep running.
  • try_recv never blocks — returns .none when empty.
  • Channels are not cloneable — pass the handle by value/move.
import std.chan
import std.task
// Simple producer/consumer
func main() -> Result<int, str> {
c := chan()
task.spawn(|_| -> Result<int, str> {
chan.send(c, 42)
return .ok(0)
})
v: int = chan.recv(c)
println(v) // 42
return .ok(0)
}
  • Do not share mutable state except via chan/task/cell.
  • Re-bind immediately after free_port-style TOCTOU helpers; retry on collision.
  • Mark tests touching global state @test(tag = "serial").
import std.task
import std.chan
c := chan()
for i in 0..8 {
task.spawn(|_| { chan.send(c, i * i) })
}
for i in 0..8 {
v: int = chan.recv(c)
println(v)
}
h := task.spawn(|_| { 21 * 2 })
r: Result<int, str> = task.join(h) // panics inside surface as .err
q := task.try_join(h) // .some when done, .none while running

4 entries. Signatures come from the compiler’s own FuncSig table, so they match the runtime exactly; descriptions come from the module guide.

Function Signature Description
std.chan.recv recv<T>(ch: chan) -> T Block for a value
std.chan.send send<T>(ch: chan, v: T) -> unit Push a value (never blocks)
std.chan.try_recv try_recv<T>(ch: chan) -> Option<T> Poll, never blocks
std.chan chan() -> chan Create a channel
  • std.task — Green threads: spawn, join and await.

Full index: API reference · Standard library