这是 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()
返回的 channel 接收的,所以第二个 worker()
在从第一个接收到一个值之前无法启动,这需要 3 秒。
您正在使用元组分配。 Spec: Assignments:
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.
和 Spec: Order of evaluation:
...when evaluating the operands of an expression, assignment, or return statement, all function calls, method calls, and communication operations are evaluated in lexical left-to-right order.
先启动2个worker,然后然后 从 channel 接收,所以 goroutine 可以真正并发运行:
ch1, ch2 := worker(), worker()
_, _ = <-ch1, <-ch2
有了这个,输出将是(在 Go Playground 上试试):3
关于go - 如何在 3 秒内打印此 Go 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63485445/