下一个 goroutine 何时执行?

huangapple go评论76阅读模式
英文:

When next goroutine is executed?

问题

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

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

    // 将sq工作分布到两个同时从in中读取的goroutine中。
    c1 := sq(in)

    // 这行代码`c2 := sq(in)`何时执行?`in`中有什么?
    c2 := sq(in)

    // 从c1和c2中消费合并的输出。
    for n := range merge(c1, c2) {
        fmt.Println(n) // 4然后9,或者9然后4
    }
}

c2 := sq(in)何时运行?据我理解,它不是在前一行完成后执行,而是立即执行,因为它是一个goroutine。

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

英文:

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

得分: 0

你的代码没有使用goroutines,要使用goroutines,你应该像这样做:

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完成。

英文:

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 &lt;- valueFromIn
     ...
}

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

huangapple
  • 本文由 发表于 2017年4月3日 17:23:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/43180936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定