doudou3716 2017-04-03 09:23 采纳率: 100%
浏览 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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名