如何在 3 秒内打印出这段 Go 代码?
How to make this Go code print in 3 seconds?
这是 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()
返回的通道接收数据,因此第二个 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.
...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,然后 从通道接收,因此 goroutine 可以真正 运行 并发:
ch1, ch2 := worker(), worker()
_, _ = <-ch1, <-ch2
这样,输出将是(在 Go Playground 上尝试):
3
您也可以删除频道,因为您没有使用频道的结果,只需使用 sync.WaitGroup
func worker(n int, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(3 * time.Second)
fmt.Println("done")
}
func main() {
timeStart := time.Now()
var wg sync.WaitGroup
for i := 0; i <= 1; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println(int(time.Since(timeStart).Seconds())) // 3
}
这是 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()
返回的通道接收数据,因此第二个 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.
...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,然后 从通道接收,因此 goroutine 可以真正 运行 并发:
ch1, ch2 := worker(), worker()
_, _ = <-ch1, <-ch2
这样,输出将是(在 Go Playground 上尝试):
3
您也可以删除频道,因为您没有使用频道的结果,只需使用 sync.WaitGroup
func worker(n int, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(3 * time.Second)
fmt.Println("done")
}
func main() {
timeStart := time.Now()
var wg sync.WaitGroup
for i := 0; i <= 1; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println(int(time.Since(timeStart).Seconds())) // 3
}