This Go program:
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
sleep_durations := []int{8100, 1000, 2500, 500, 6000}
// sleep_durations := []int{8100, 1000, 2500, 500}
c := make(chan string)
defer close(c) // close channel when main exits
for index, duration := range sleep_durations {
go sleepy(fmt.Sprintf("sleepy%d: ", index+1), duration, c)
}
fmt.Printf("starting %d sleepys\n", len(sleep_durations))
for range sleep_durations {
select {
case msg := <-c:
fmt.Println("received: ", msg)
case <-time.After(time.Second * time.Duration(5)):
fmt.Println("*** TIMEOUT ***")
}
}
elapsed := time.Since(start)
fmt.Printf("... %d sleepys ran in: %e\n", len(sleep_durations), elapsed.Seconds())
}
func sleepy(msg string, sleep_ms int, yawn chan string) {
start := time.Now()
sleep := time.Duration(sleep_ms) * time.Millisecond
time.Sleep(sleep) // some sleepy work
yawn <- fmt.Sprintf("%s slept for %s", msg, sleep)
elapsed := time.Since(start)
fmt.Printf("\t%s finished in: %s\n", msg, elapsed)
}
https://play.golang.org/p/0ioTuKv230
has confusing results. When line 11 is uncommented it does not work as expected, i.e. the time.After 5 seconds doesn't happen. But with line 11 commented and line 12 uncommented the timeout does work as expected. I'm new to Go, but what am I missing?
time.Afterchannel outside of the loop, you'd see the timeout code run. Whether that's the right thing to do in real life depends on your application.