go - 如何在 3 秒内打印此 Go 代码?

标签 go time concurrency channel goroutine

这是 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/

相关文章:

go - 处理程序服务后,如何从请求对象取回记录器对象?

go - 使用不带命令的 PTY

java - 需要有关 java 中 ExecutorService 的建议

c# - MSMQ并发处理设计问题

multithreading - 一个 Rust 闭包可以被多个线程使用吗?

Golang 比较数字

go - 使用 Go 读写 Yaml 文件

time - Ada 中任务的 CPU 时间

string - R:变换不规则时间串

json - 使用按钮更新用户位置并快速绘制路线