下一个 goroutine 何时执行?

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

When next goroutine is executed?

问题

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

  1. func main() {
  2. in := gen(2, 3)
  3. // 将sq工作分布到两个同时从in中读取的goroutine中。
  4. c1 := sq(in)
  5. // 这行代码`c2 := sq(in)`何时执行?`in`中有什么?
  6. c2 := sq(in)
  7. // 从c1和c2中消费合并的输出。
  8. for n := range merge(c1, c2) {
  9. fmt.Println(n) // 4然后9,或者9然后4
  10. }
  11. }

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

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

英文:

I am looking at the example from https://blog.golang.org/pipelines:

  1. func main() {
  2. in := gen(2, 3)
  3. // Distribute the sq work across two goroutines that both read from in.
  4. c1 := sq(in)
  5. // When does this line below execute and what is in `in`?
  6. c2 := sq(in)
  7. // Consume the merged output from c1 and c2.
  8. for n := range merge(c1, c2) {
  9. fmt.Println(n) // 4 then 9, or 9 then 4
  10. }
  11. }

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,你应该像这样做:

  1. q := make(chan type)
  2. go sq(in, q)
  3. go sq(in, q)
  4. for elem := range q {
  5. fmt.Println(elem)
  6. }

并且sq函数必须通过一个通道返回值:

  1. func sq(in type, q chan type) {
  2. // ...
  3. q <- valueFromIn
  4. // ...
  5. }

此外,你可以使用WaitGroup来等待goroutines完成。

英文:

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

  1. q := make(chan type)
  2. go sq(in, q)
  3. go sq(in, q)
  4. for elem := range q {
  5. fmt.Println(elem)
  6. }

and sq must return the value through a channel

  1. func sq(in type, q chan type) {
  2. ...
  3. q &lt;- valueFromIn
  4. ...
  5. }

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:

确定