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

标签 go concurrency goroutine

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

Golang 中 goroutine 和 channel 的初学者。

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
}

最佳答案

enter image description here

希望有帮助。它是goroutine的管道图。所以有三个 goroutine 和两个 channel

关于go - 给定代码的执行流程将如何? go 例程在这里将如何执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58692089/

相关文章:

xml - 只定义一个结构并让它在 Go 中处理 XML 文件的所有内部元素?

go - 没有任何 goroutine 但仍然得到 "all goroutines are asleep -deadlock"

Scala future 基础知识

android - 线程并发 wait() 其他线程完成并继续其工作

go - 如何使用 Sarama 在多个 goroutine 中消费 Kafka 主题?

go - strings.Split 从不返回 nil 或零长度 slice ?

linux - 在 golang 中写在热敏打印机设备上

java - 在其他几个任务完成后运行该任务

go - 在golang中打开超时的PE文件

go - 使用 goroutine 验证 Golang 中的结构