Skip to content

Instantly share code, notes, and snippets.

@r4um
Forked from x32net/wait_timeout.go
Created July 7, 2017 13:55
Show Gist options
  • Save r4um/c1ab51b8757fc2d75d30320933cdbdf6 to your computer and use it in GitHub Desktop.
Save r4um/c1ab51b8757fc2d75d30320933cdbdf6 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