如何在3秒内打印出该Go代码? [英] How to make this Go code print in 3 seconds?

查看:45
本文介绍了如何在3秒内打印出该Go代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是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秒内执行?

How can I make this execute in 3 seconds rather than executing in 6 seconds?

推荐答案

这需要6秒钟,因为您是从 worker()返回的频道接收的,所以第二个 worker()不能启动,直到从第一个接收到一个值,这需要3秒钟.

It takes 6 seconds because you are receiving from the channel returned by worker(), so the 2nd worker() cannot be started until a value is received from the first, which takes 3 seconds.

您正在使用元组分配.规范:分配:

You are using a tuple assignment. 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.

规范:评估顺序:

...评估表达式,赋值或操作数时="https://golang.org/ref/spec#Return_statements" rel ="nofollow noreferrer"> return语句,所有函数调用,方法调用和通讯操作均按从左到右的词法进行评估-正确的订单.

...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个工作程序,然后然后从渠道接收消息,因此goroutine可以真正同时运行:

Launch the 2 workers first, and then receive from the channels, so the goroutines can truly run concurrently:

ch1, ch2 := worker(), worker()
_, _ = <-ch1, <-ch2

使用此命令,输出将是(在游乐场上尝试):

With this, output will be (try it on the Go Playground):

3

这篇关于如何在3秒内打印出该Go代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆