Context.wait
func Context.wait(ctx: Context): voidContext.wait blocks until ctx is done.
Details
waitreturns at once whenctxis done already.- A context that nothing cancels and that has no deadline is done only when its parent is, so a wait on it can last until the run ends.
waittakes no context of its own. To bound it, wait on a child with a timeout instead.- Every write a goroutine makes before
Context.cancelis visible after thewaitthat the cancel ends returns. Context.wait(ctx)is a head ofselect, which can proceed once the context is done.
Basic examples
Wait for a context's timeout to pass:
let ctx = Context.new(timeout: 20ms)
Context.wait(ctx)
println(ctx.reason())timeoutWait until another goroutine cancels the context:
let ctx = Context.new()
go {
Time.sleep(20ms)
ctx.cancel()
}
Context.wait(ctx)
println(ctx.reason())cancelledScope
A context that is done already has nothing to wait for, so wait returns at once:
let ctx = Context.new()
ctx.cancel()
ctx.wait()
println("returned at once")returned at onceA child is done when its parent is, with the parent's reason, so a wait on the child ends when the parent is cancelled:
let parent = Context.new()
let child = Context.new(timeout: 1h, parent: parent)
go {
Time.sleep(20ms)
parent.cancel()
}
child.wait()
println(child.reason())cancelledAny number of goroutines can wait on one context, and one cancel releases all of them. Here the context works as a starting gate:
let gate = Context.new()
let started = Atomic.new(0)
let runners = WaitGroup.new()
for _ in Array.range(0, 3) {
runners.add(1)
go {
defer { runners.done() }
gate.wait()
started.add(1)
}
}
println("started before the gate opens: ${started.load()}")
gate.cancel()
runners.wait()
println("started after: ${started.load()}")started before the gate opens: 0
started after: 3The context of Os.interrupt is done at Ctrl-C, so a wait on it lasts until the user stops the program:
let stop = Os.interrupt()
println("press Ctrl-C to stop")
stop.wait()
println("stopped: ${stop.reason()}")press Ctrl-C to stop
stopped: interruptIn a select, Context.wait(ctx) is a head that can proceed once the context is done. Beside a receive it ends the wait for a value that does not come in time:
let replies: Channel[string] = Channel.new()
let ctx = Context.new(timeout: 20ms)
let reply = select {
let r = Channel.receive(replies) { r ?? "closed" }
Context.wait(ctx) { "no reply: ${ctx.reason()}" }
}
println(reply)no reply: timeoutApplications
Serve until Ctrl-C
Run a server on its own goroutine and keep the main goroutine waiting for the interrupt. The server sees the same context, and the main goroutine waits for it to finish the requests in flight:
func hello(req: Http.Request): Http.Reply {
Http.Reply{ status: 200, headers: Map{}, body: "hi" }
}
let stop = Os.interrupt()
let listener = try Net.listen("127.0.0.1:0")
let served = WaitGroup.new()
served.add(1)
go {
defer { served.done() }
_ = Http.serve(listener, hello, ctx: stop)
}
println("serving")
stop.wait()
println("shutting down")
served.wait()serving
shutting downStop a worker loop
A worker that waits on several things writes a select in a loop, with a Context.wait clause that returns when the work is cancelled:
func work(jobs: Channel[string], ctx: Context) {
while true {
select {
Context.wait(ctx) {
println("stopped: ${ctx.reason()}")
return
}
let job = Channel.receive(jobs) {
if job == null { return }
println("done ${job}")
}
}
}
}
let jobs: Channel[string] = Channel.new()
let ctx = Context.new()
let wg = WaitGroup.new()
wg.add(1)
go {
defer { wg.done() }
work(jobs, ctx)
}
for job in ["resize", "upload"] {
jobs.send(job)
}
ctx.cancel()
wg.wait()done resize
done upload
stopped: cancelledWait with a limit
wait takes no context, so bound it with a child that has a timeout. The child is done when the parent is or when the time passes, and the parent's isDone tells which:
func waitAtMost(ctx: Context, limit: Time.Duration): bool {
Context.new(timeout: limit, parent: ctx).wait()
ctx.isDone()
}
let job = Context.new()
println(waitAtMost(job, 20ms))
job.cancel()
println(waitAtMost(job, 1s))false
trueProperties and relations
Once wait returns, the context is done and has a reason:
let ctx = Context.new(timeout: 10ms)
ctx.wait()
assert(ctx.isDone())
assert(ctx.reason() == "timeout")What a goroutine writes before it cancels a context is visible after the wait returns, so a cancel can hand over a result:
let result = ["pending"]
let ready = Context.new()
go {
result[0] = "computed"
ready.cancel()
}
ready.wait()
assert(result[0] == "computed")Context.wait(ctx) waits as a select with that one head does:
let a = Context.new(timeout: 10ms)
a.wait()
let b = Context.new(timeout: 10ms)
select {
Context.wait(b) {}
}
assert(a.reason() == b.reason())Possible issues
A context nothing ends
A context without a timeout is done only when a call cancels it or its parent is done. If nothing does, a wait on it lasts until the run ends. Cancelling a child does not end the parent either. Here a bounded wait shows that the parent is still running:
let parent = Context.new()
let child = Context.new(parent: parent)
child.cancel()
Context.new(timeout: 20ms, parent: parent).wait()
println(parent.isDone())falseNo context argument
The one parameter of wait is ctx, the context it waits for, so ctx: names it a second time. To bound the wait, wait on a child with a timeout, as in Wait with a limit:
let job = Context.new()
let limit = Context.new(timeout: 1s)
Context.wait(job, ctx: limit) // error: the parameter ctx is given twiceHeads in a select
A select head is written in the namespace form. ctx.wait() is the same call elsewhere, but in a select it is a syntax error:
let ctx = Context.new(timeout: 10ms)
select {
ctx.wait() { println("done") }
// error: a select clause's head must be a call of Channel.receive, Channel.send, Context.wait, WaitGroup.wait or Time.sleep
}A Context.wait head binds nothing, since wait returns void:
let ctx = Context.new(timeout: 10ms)
select {
let r = Context.wait(ctx) { println("done") } // error: Context.wait returns void, so there is nothing to bind to r
}See also
Context.new · Context.cancel · Context.isDone · Context.reason · Context · Os.interrupt · WaitGroup.wait · Time.sleep · select · Concurrency guide
