Skip to content

Instantly share code, notes, and snippets.

@padurean
Forked from r4um/wait_timeout.go
Created January 5, 2022 16:17
Show Gist options
  • Save padurean/28476f35eb5e2cbc1e4a430ac76f0b57 to your computer and use it in GitHub Desktop.
Save padurean/28476f35eb5e2cbc1e4a430ac76f0b57 to your computer and use it in GitHub Desktop.
Golang - WaitGroup Timeout
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
wg.Add(1)
timeout := time.Second
fmt.Printf("Wait for waitgroup (up to %s)\n", timeout)
if waitTimeout(&wg, timeout) {
fmt.Println("Timed out waiting for wait group")
} else {
fmt.Println("Wait group finished")
}
fmt.Println("Free at last")
}
// waitTimeout waits for the waitgroup for the specified max timeout.
// Returns true if waiting timed out.
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
c := make(chan struct{})
go func() {
defer close(c)
wg.Wait()
}()
select {
case <-c:
return false // completed normally
case <-time.After(timeout):
return true // timed out
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment