Skip to main content

Module context

Module context 

Source
Expand description

Cancellation and deadline propagation — equivalent to Go’s context package.

§Quick start

use go_lib::context;
use std::time::Duration;

go_lib::run(|| {
    // Root context — never cancels on its own.
    let bg = context::background();

    // Child with explicit cancel.
    let (ctx, cancel) = context::with_cancel(&bg);

    go_lib::go!(move || {
        // Worker loops until the context is done.
        loop {
            go_lib::select! {
                recv(ctx.done()) -> _v => { break }
                default => { /* do work */ go_lib::gosched(); }
            }
        }
    });

    go_lib::sleep(Duration::from_millis(10));
    cancel.cancel(); // signal the worker to stop
});

§Design

Each Context is a thin Arc wrapper around a ContextInner that holds:

  • An optional deadline: Instant.
  • A done channel (Receiver<()>) that fires (returns None) when the context is cancelled or its deadline elapses.
  • A children list so cancellation propagates from parent to child.

Cancellation closes the done channel by dropping its internal Sender<()>. Closed channels return None from recv(), which fires any select! arm that waits on them — the standard Go done-channel idiom.

§Requirements

with_deadline / with_timeout spawn a timer goroutine and therefore require the go-lib scheduler to be running (i.e. called from inside [go_lib::run]). background() and with_cancel() are safe to call from anywhere.

Structs§

CancelFn
Cancels the associated Context when called.
Context
A context value carrying a cancellation signal and optional deadline.

Enums§

ContextError
Why a context was cancelled.

Functions§

background
Return a background context: it is never cancelled and has no deadline.
with_cancel
Return a child context and a cancel function.
with_deadline
Return a child context that is automatically cancelled at deadline.
with_timeout
Return a child context that is automatically cancelled after timeout.