下一个goroutine什么时候执行?

When next goroutine is executed?

我正在查看 https://blog.golang.org/pipelines 中的示例:

func main() {
    in := gen(2, 3)

    // Distribute the sq work across two goroutines that both read from in.
    c1 := sq(in)

    // When does this line below execute and what is in `in`?
    c2 := sq(in)

    // Consume the merged output from c1 and c2.
    for n := range merge(c1, c2) {
        fmt.Println(n) // 4 then 9, or 9 then 4
    }
}

什么时候c2 := sq(in)运行?据我了解,它不是在上一行完成时执行,而是立即执行,因为那是一个 goroutine。

c2 会收到 c1 收到的消息之后的下一条传入消息吗?

你的代码不使用 goroutines,为了使用 go routines 你应该这样做:

q := make(chan type) 
go sq(in, q)
go sq(in, q)

for elem := range q {
    fmt.Println(elem)
}

并且 sq 必须 return 通过通道

的值
func sq(in type, q chan type) {
     ...
     q <- valueFromIn
     ...
}

您也可以使用 WaitGroup 等待 goroutines 完成。