-
-
Save padurean/28476f35eb5e2cbc1e4a430ac76f0b57 to your computer and use it in GitHub Desktop.
Golang - WaitGroup Timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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