这个围棋程序:
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
有令人困惑的结果。当第 11 行被取消注释时,它不会按预期工作,即time.After5 秒不会发生。但是在第 11 行注释和第 12 行取消注释后,超时确实按预期工作。我是 Go 的新手,但我错过了什么?
海绵宝宝撒
相关分类