WaitGroup.add
func WaitGroup.add(wg: WaitGroup, n: int): voidWaitGroup.add adds n, which may be negative, to the counter of wg. It panics if the counter would go negative or past [Math.maxInt].
Details
- Call
addbefore thegothat starts the work, not inside it. Awaitthat runs while the counter is zero returns at once. add(wg, -1)takes one off the counter, asdonedoes. A goroutine signals that it finished withdone.- A negative
addthat brings the counter to zero releases everyWaitGroup.waitonwg, and what the goroutine wrote before it is visible oncewaitreturns, as withdone.
Basic examples
Add one to the counter for each goroutine before starting it. Each goroutine calls done when it finishes, and wait returns when the counter is back at zero:
let wg = WaitGroup.new()
let lengths = Array.filled(3, 0)
for entry in ["ant", "bee", "wasp"].entries() {
WaitGroup.add(wg, 1)
go {
defer { wg.done() }
lengths[entry.index] = entry.value.length()
}
}
wg.wait()
println(lengths)[3, 3, 4]Add the whole batch at once when its size is known up front:
let words = ["red", "green", "blue"]
let wg = WaitGroup.new()
let upper = Array.filled(words.length(), "")
WaitGroup.add(wg, words.length())
for entry in words.entries() {
go {
defer { wg.done() }
upper[entry.index] = entry.value.toUpper()
}
}
wg.wait()
println(upper)["RED", "GREEN", "BLUE"]Scope
n may be zero, which changes nothing, or negative, which takes work off the counter:
let wg = WaitGroup.new()
wg.add(0)
wg.add(3)
wg.add(-3)
wg.add(-1) // panic: WaitGroup.add: the counter would go negativeA wait group in a record field counts the work of that record. Here a server counts the requests it is handling, so close can wait for them:
type Server = { name: string, active: WaitGroup = WaitGroup.new(), served: Atomic[int] = Atomic.new(0) }
func Server.handle(s: Server, request: string) {
s.active.add(1)
go {
defer { s.active.done() }
Time.sleep(5ms)
s.served.add(1)
}
}
func Server.close(s: Server) {
s.active.wait()
println("${s.name} closed after ${s.served.load()} requests")
}
let server = Server{ name: "api" }
for request in ["/", "/users", "/health"] {
server.handle(request)
}
server.close()api closed after 3 requestsApplications
Reserve the whole batch, then give back the items that need no goroutine with a negative add:
let inputs = ["12", "", "7", "", "30"]
let wg = WaitGroup.new()
let total = Atomic.new(0)
wg.add(inputs.length())
for input in inputs {
if input.isEmpty() {
wg.add(-1)
continue
}
go {
defer { wg.done() }
total.add(input.toInt() ?? 0)
}
}
wg.wait()
println(total.load())49A goroutine may start more work and add it to the same group, as long as it adds before its own done. The counter then never reaches zero early:
let wg = WaitGroup.new()
let visited = Atomic.new(0)
func visit(depth: int): void {
visited.add(1)
if depth == 0 { return }
for _ in Array.range(0, 2) {
wg.add(1)
go {
defer { wg.done() }
visit(depth - 1)
}
}
}
wg.add(1)
go {
defer { wg.done() }
visit(3)
}
wg.wait()
println(visited.load())15Properties and relations
add(wg, -1) and done both take one off the counter, so after both a wait returns at once:
let wg = WaitGroup.new()
wg.add(2)
wg.done()
wg.add(-1)
wg.wait()
println("counter is back at zero")counter is back at zeroPossible issues
An add inside the goroutine comes too late. Here the goroutine has not run its add yet, so the counter is zero and wait returns before the work is done:
let wg = WaitGroup.new()
let start: Channel[bool] = Channel.new()
let finished = Atomic.new(false)
go {
start.receive()
wg.add(1)
defer { wg.done() }
finished.store(true)
}
wg.wait()
println("finished: ${finished.load()}")
start.send(true)finished: falseAn add with no matching done keeps the counter above zero, and a wait without a context never returns. A context bounds the wait, and Context.isDone reports whether it gave up:
let wg = WaitGroup.new()
wg.add(2)
go { wg.done() }
let ctx = Context.new(timeout: 50ms)
wg.wait(ctx: ctx)
println(if ctx.isDone() { "gave up: one done is missing" } else { "all done" })gave up: one done is missingSee also
WaitGroup.done · WaitGroup.wait · WaitGroup.new · WaitGroup · Parallel.each · Atomic · defer · Concurrency guide
