doudou3716
2017-04-03 09:23
采纳率: 0%
浏览 46
已采纳

什么时候执行下一个goroutine?

I am looking at the example from 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
    }
}

When does c2 := sq(in) run? As what I understand, it executes not when previous line finishes, but instantly as that is a goroutine.

Will c2 receive the next incoming message that is after coming after the message that is received by c1?

图片转代码服务由CSDN问答提供 功能建议

我正在查看 https://blog.golang.org/pipelines

  func main(){
 in:= gen(2  ,3)
 
 //将sq工作分配到两个均从in读取的goroutine中。
 c1:= sq(in)
 
 //下面的这一行何时执行以及in中的内容 ?
 c2:= sq(in)
 
 //消耗c1和c2的合并输出。
为n:= range merge(c1,c2){
 fmt.Println(n)// 4 然后9或9然后4 
} 
} 
   
 
 

c2:= sq(in)何时运行? 据我了解,它不是在上一行结束时执行,而是立即执行。

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doukeyong3746487 2017-04-03 15:51
    已采纳

    Your code does not use goroutines, in order to use go routines you should do something like this:

    q := make(chan type) 
    go sq(in, q)
    go sq(in, q)
    
    for elem := range q {
        fmt.Println(elem)
    }
    

    and sq must return the value through a channel

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

    Also you can use WaitGroup to wait for goroutines to finish.

    打赏 评论

相关推荐 更多相似问题