【问题标题】:When next goroutine is executed?下一个 goroutine 什么时候执行?
【发布时间】:2017-04-03 09:23:50
【问题描述】:

我在看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
    }
}

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

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

【问题讨论】:

  • 不,它在上一行完成时执行。没有go,所以它不是一个goroutine。 (gen 函数可以启动一个 goroutine,但它是完全独立的并且在后台运行。)

标签: go goroutine


【解决方案1】:

您的代码不使用 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 等待 goroutine 完成。

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2017-02-20
    • 2016-01-07
    相关资源
    最近更新 更多