- Bounded waiting (timeout)
- Avoid unbounded waiting
func main() {
timeout := 5 * time.Second
done := make(chan struct{}, 1)
go doSlowTask(done)
// -- Wait for first of ...
select {
case <-done:
// -- wait for task to finish
fmt.Println("Finished task")
case <-time.After(timeout):
// -- wait for timer
fmt.Println("Timeout")
}
}
func doSlowTask(done chan<- struct{}) {
defer func() { done <-struct{} }()
time.Sleep(3 * time.Second)
}