2017-04-03 44 views
-4

我从https://blog.golang.org/pipelines看一下例子:当下一个goroutine被执行时?

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

+5

不,它在上一行结束时执行。没有'go',所以这不是一个门厅。 ('gen'函数可能会启动一个goroutine,但它完全独立并在后台运行。) – psmears

回答

0

你的代码不使用够程,为了使用去例程,你应该做这样的事情:

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

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

和SQ必须通过一个通道

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

您也可以返回值使用WaitGroup来等候goroutines完成。

相关问题