【发布时间】:2020-12-08 15:09:37
【问题描述】:
这是 Go 代码 https://www.intervue.io/sandbox-ILSCXZ6RR
func worker() chan int {
ch := make(chan int)
go func() {
time.Sleep(3 * time.Second)
ch <- 42
}()
return ch
}
func main() {
timeStart := time.Now()
_, _ = <-worker(), <-worker()
println(int(time.Since(timeStart).Seconds())) // 3 or 6 ?
}
我怎样才能让它在 3 秒内执行而不是在 6 秒内执行?
【问题讨论】:
-
代码在 6 秒内运行,因为你运行了两次 worker。 3+3 = 6s
标签: go time concurrency channel goroutine