Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Channels

A Channel passes Var values between threads or tasks. send puts a value in. receive or foreach takes values out until the channel is closed and drained.

Plain send lends the value: the sender keeps ownership and keeps the value alive while receivers use it. send_owned hands one container’s storage to the receiver. The application is responsible for independent nested lifetimes, aliases, and coordinated mutable access.

Send, close, and drain

send blocks until the channel accepts a message. receive blocks until a message is available, or returns void after normal closure and draining. Iteration receives until that exhaustion. Null and nil are ordinary data.

The sender explicitly closes a stream when no more messages will arrive. With several senders, a coordinator closes after all senders finish. Closing is idempotent, rejects new sends, wakes waiters, and preserves accepted messages for draining. It does not acknowledge that consumers finished using a payload.

int main(void) {
  Channel numbers = auto Channel.new(<i32>, 2);
  int total = 0;

  Thread.run([
    %!(void) => {
      for (int i = 1; i <= 4; ++i) numbers.send(i);
      numbers.close();
    },
    %!(void) using &total => {
      foreach (int value in numbers) total += value;
    }
  ]);

  printf("%d\n", total);
  return 0;
}
10

Choose capacity and message constraint

ConstructorBehavior
Channel.new()Any non-void Var, rendezvous.
Channel.new(4)Any non-void Var, at most four buffered messages.
Channel.new(<map>)Exact Map tag, rendezvous.
Channel.new(<i32>, 4)Exact signed 32-bit integer tag, four buffered messages.
Channel.new(<var>, <unbounded>)Any non-void Var, no configured buffer bound.
Channel.new(<unbounded>)The same unrestricted unbounded channel.

Rendezvous capacity is zero: send and receive commit together when matched. Positive integer capacity bounds accepted queued messages. Unbounded channels can fail allocation. Capacity does not bound storage retained by messages or canonical pools.

A constraint is an exact Var tag, not a conversion request. For example, <i32> accepts an int; a long has a different tag. <var> removes the constraint. A correctly tagged null handle is accepted by its constraint. void is always rejected because it denotes exhausted reception. Unknown tags and invalid capacities raise <bad-arg>; mismatched messages raise <bad-types>.

Buffered messages keep FIFO queue order. No fairness order is promised among competing senders or receivers. Successful send means acceptance, not completed processing.

Borrow or hand off storage

Ordinary send(value) copies Var representation bits. The sender keeps ownership, and the application keeps storage alive for every borrower. For example, the application can send the same parent-owned Map to several readers without transferring it and prevent writes until those readers finish. Send acceptance is not evidence that any borrower has finished using the object.

Use send_owned when a worker produces a Map whose storage must survive worker exit. Ordinary Map and Array values start with records and buffers in their current allocation owner and no owned-content scope. The send creates a transport Scope only for that handoff and moves the record, buffers, and any owned contents into it:

Map part = word_count(filename);
results.send_owned(part);

This is physical storage movement, not traversal of keys, elements, or referenced objects. The transport scope stays detached while queued. Do not move a payload into channel.scope() yourself; that scope is not a shared destination for senders.

On failed send, ordinary container records, buffers, and owned contents return to their original allocation owner. An owned-content scope also regains its exact original parent, including a deliberately separate or detached owner. The empty transport Scope is destroyed before the error is raised. Failures before preparation leave ownership unchanged.

On successful acceptance, the sender relinquishes access and cleanup. A subtree must not be sent twice. Do not leave a separate initializer auto or deferred cleanup armed for it; sending cannot disarm cleanup that is already armed. Unrelated aliases do not disappear when ownership changes.

Receipt moves ordinary Map or Array storage into the receiver’s active Scope and destroys the empty transport Scope before returning. The receiver may clean up the container directly or move its complete storage to another owner. If the receiver fails, cleanup of its active Scope reclaims the received storage.

The automatic path handles ordinary Map and Array tags. A typed container or other custom value needs a scope that the caller prepares: a scope that nothing else uses, that is not active, and that holds all of the value’s storage. For example, prepare a packed ArrayInt with move_to:

ArrayInt values = ArrayInt.new();
values.push(17);
Scope transport = Scope.new();
values.move_to(&transport);
results.send_owned(values);

Until acceptance the caller owns this prepared scope. Failure restores its original parent; a prepared detached scope stays detached and caller-owned. After acceptance it belongs to the queue, then becomes a child of the receiver’s active Scope. The value sent must be a live, nonnull pointer from a Scope allocator, and its allocation owner must be that prepared scope. The operation does not discover pointer provenance or validate an object graph. Canonical Strings and Lists, ordinary scalars, borrowed buffers, and interior pointers do not meet that requirement.

Nested mutable values keep independent ownership unless explicitly moved into the container’s owned contents before handoff. Calling scope() creates that owned-content scope lazily; it does not group the record or buffers. Move a nested container’s complete storage with move_to, rather than moving only its content scope. Private-pool String keys do not become safe when their Map moves. Shared process-pool String values stay borrowable; see Interned values outlive workers.

channel.scope() returns the Channel’s own storage scope, which owns its native mutex and condition. A native thread that waits on a Channel blocks. A task that waits is suspended so another task can run.

Finish every user and waiter before freeing a Channel or destroying its owner. Cleanup explicitly destroys undelivered owned subtrees and frees native queue nodes outside the queue mutex. It never destroys ordinary borrowed payloads. Initializer auto closes and frees the Channel; it does not join its users. Thread.run finishes every participant before surrounding Channel cleanup on success or failure. Parent-scope destruction uses the same native-resource finalizer.

Failure and cooperative stopping

A Channel has no task-failure state. Thread.run observes a failed job, stops all remaining jobs before joining them, and preserves the triggering error. Blocked Channel operations wake on their own Thread’s stop request and unwind after releasing queue locks. They do not report successful exhaustion.

A send commits when the Channel accepts its value, and a receive commits when it takes a value. A committed send or receive succeeds despite a later stop. A pending stop before commitment prevents that operation and raises the Thread stop cause. A stopped rendezvous participant cannot be matched by another operation.

Thread stopping does not close Channels or stop unrelated users. A stop does not interrupt computation or arbitrary native I/O. Keep a cancelled client’s request bytes alive until the service finishes borrowing them. The owner can outlive the whole batch if that is the simplest arrangement.

Batch jobs use the shared process canonical pool by default. Interned String values there outlive the jobs and stay until process shutdown, as Interned values outlive workers describes. Explicit private pools keep their own lifetime obligations. Sending a value does not intern or copy its contents.

Where to go next