-
-
Save r4um/c1ab51b8757fc2d75d30320933cdbdf6 to your computer and use it in GitHub Desktop.
Golang - WaitGroup Timeout
This file contains 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