WaitGroup Wait With A Timeout
Convert wg.Wait into a channel receive so select can race completion against a deadline, and see that timed-out workers keep running without one.
Code
package main
import (
"fmt"
"sync"
"time"
)
// waitForGroup turns wg.Wait into a single channel receive,
// which lets select wait on completion and timeout at the same time
func waitForGroup(wg *sync.WaitGroup) <-chan struct{} {
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
return done
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func() { // since Go 1.22 each iteration gets a fresh i
defer wg.Done()
time.Sleep(time.Duration(10*i) * time.Millisecond)
fmt.Println("worker", i, "finished")
}()
}
select {
case <-waitForGroup(&wg):
fmt.Println("all workers joined in time")
case <-time.After(150 * time.Millisecond):
fmt.Println("timeout: workers still running")
}
// a long task overshoots the budget: the timeout branch returns, but the worker is not cancelled,
// it needs its own cancellation; at process exit an unjoined worker is simply killed
var slow sync.WaitGroup
slow.Add(1)
go func() {
defer slow.Done()
time.Sleep(400 * time.Millisecond)
fmt.Println("slow worker finished")
}()
select {
case <-waitForGroup(&slow):
fmt.Println("slow batch joined")
case <-time.After(150 * time.Millisecond):
fmt.Println("timeout: slow batch exceeded budget")
}
}Reading the code as it runs
WaitGroup Wait With A Timeout keeps everything in the functions waitForGroup and main.
The cycling part of this snippet is for i := 1; i <= 3; i++. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Applying it
Entry signature: func waitForGroup(wg *sync.WaitGroup) <-chan struct
The run emits 6 labeled sections — worker, all workers joined in time, timeout: workers still running, slow worker finished, slow batch joined, timeout: slow batch exceeded budget — one per step.
The sequence waitForGroup lives in main; running the file triggers it.
Statements that matter
func waitForGroup(wg *sync.WaitGroup) <-chan struct{} {
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
return done
}
go func() { // since Go 1.22 each iteration gets a fresh i
defer wg.Done()
time.Sleep(time.Duration(10*i) * time.Millisecond)
fmt.Println("worker", i, "finished")
}()
var slow sync.WaitGroup
Interactive Tools for This Topic
FAQ
- What does WaitGroup Wait With A Timeout print when run?
- Running the file directly is enough — expect labeled output lines such as `worker`, `all workers joined in time`, `timeout: workers still running`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.