ctx
A context for cancellation and deadlines, passed from the main piece of work down to the smaller ones.
import ctx
A context tells long-running work when to stop: either someone called Cancel, or its deadline passed. Contexts form a tree: you start from Background and make a child each time with WithCancel, WithTimeout or WithDeadline.
Cancelling a context ends all its children, but not its parent. The work should check IsDone from time to time, or wait on it with Wait. Free each context with Free when you are done with it, children before parents.
Types
Context
struct Context| Name | Type | Description |
|---|---|---|
state | i64* | The internal state: cancelled, the deadline and whether there is one. |
parent | Context* | The parent context, or null for the root. |
mu | sync.Mutex | The lock every context in one tree shares. |
cv | sync.CondVar | The condition variable that cancellation wakes. |
is_root | bool = false | Whether this context is the root. |
import ctx
func main:
root := ctx.Background()
cancellable := ctx.WithCancel(root)
timed := ctx.WithTimeout(cancellable, 30)
println ctx.IsDone(timed), "[" + ctx.Err(timed) + "]", ctx.Deadline(timed) > 0, ctx.Deadline(root)
println ctx.Wait(timed, 10)
println ctx.Wait(timed, 1000), ctx.Err(timed)
ctx.Cancel(cancellable)
println ctx.IsDone(cancellable), ctx.Err(cancellable), ctx.IsDone(root)
past := ctx.WithDeadline(root, 1)
println ctx.IsDone(past), ctx.Err(past)
ctx.Free(past)
ctx.Free(timed)
ctx.Free(cancellable)
ctx.Free(root)
endFunctions
Background
func Background(): ContextThe example for this item is shown with the ones above: ctx-Context.salam
WithCancel
func WithCancel(parent: Context): ContextCancel is called.The example for this item is shown with the ones above: ctx-Context.salam
WithTimeout
func WithTimeout(parent: Context, ms: i64): Contextms milliseconds from now.The example for this item is shown with the ones above: ctx-Context.salam
WithDeadline
func WithDeadline(parent: Context, at_ms: i64): Contextat_ms, in milliseconds, as sync.NowMs gives it.The example for this item is shown with the ones above: ctx-Context.salam
Cancel
func Cancel(c: Context)The example for this item is shown with the ones above: ctx-Context.salam
IsDone
func IsDone(c: Context): boolThe example for this item is shown with the ones above: ctx-Context.salam
Err
func Err(c: Context): strcancelled or deadline exceeded, or an empty string while it is still running.The example for this item is shown with the ones above: ctx-Context.salam
Deadline
func Deadline(c: Context): i64The example for this item is shown with the ones above: ctx-Context.salam
Wait
func Wait(c: Context, ms: i64): boolms milliseconds for the context to finish and says whether it did.The example for this item is shown with the ones above: ctx-Context.salam
Free
func Free(c: Context)The example for this item is shown with the ones above: ctx-Context.salam