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.chanPurpose
Section titled “Purpose”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.
Quickstart
Section titled “Quickstart”import std.chan
c := chan()chan.send(c, 42)v: int = chan.recv(c) // blocksopt: Option<int> = chan.try_recv(c) // .some(v) or .none, never blocksFan-out / fan-in recipe
Section titled “Fan-out / fan-in recipe”import std.taskimport 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_recvEdge cases & gotchas
Section titled “Edge cases & gotchas”- Unbounded — a fast producer can outpace a slow consumer; memory grows. Apply backpressure externally if needed.
recvblocks the task (not the OS thread) — other tasks keep running.try_recvnever blocks — returns.nonewhen empty.- Channels are not cloneable — pass the handle by value/move.
Production patterns
Section titled “Production patterns”import std.chanimport std.task
// Simple producer/consumerfunc 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").
Quickstart
Section titled “Quickstart”import std.taskimport 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 .errq := task.try_join(h) // .some when done, .none while runningAPI reference
Section titled “API reference”4 entries. Signatures come from the compiler’s own FuncSig table, so they match the runtime exactly; descriptions come from the module guide.
See also
Section titled “See also”std.task— Green threads: spawn, join and await.
Full index: API reference · Standard library