给定代码的执行流程将如何?还有 go-routines 将如何在这里执行?

How will the flow of execution of the given code will be? And also how will the go-routines will execute here?

(并发编程新手) 有疑问为什么 goroutines 的执行流程在这里有点奇怪?

golang 中的 goroutines 和通道的初学者。

func main() {
    // Set up the pipeline.
    c := gen(2, 3)
    out := sq(c)

    // Consume the output.
    fmt.Println(<-out) // 4
    fmt.Println(<-out) // 9
}

func sq(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for n := range in {
            out <- n * n
        }
        close(out)
    }()
    return out
}

func gen(nums ...int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    return out
}

一旦调用 gensq 完成,就会同时有 3 个 goroutines 运行ning。它们在通道之间传递数据,因此执行会产生相同的结果。

  1. gen-inner
  2. 平方内
  3. 主要

他们总是传递至少 2 条信息,因此 运行 他们的代码顺序如下

  1. gen-inner out <- n -2-> sq-inner out <- n * n -4-> main println(<-out)
  2. gen-inner out <- n -3-> sq-inner out <- n * n -9-> main println(<-out)

还有可能发生的第三遍,但它可能会在 main goroutine 结束时被跳过。

  1. gen-inner close() -close-> sq-inner close(out) -close->

希望对您有所帮助。它 goroutine 流水线图。所以有 3 个 goroutines 和 2 个 channels