go routine for range over channels

前端 未结 3 1090
孤街浪徒
孤街浪徒 2021-01-15 17:04

I have been working in Golang for a long time. But still I am facing this problem though I know the solution to my problem. But never figured out why is it happening.

<
3条回答
  •  天涯浪人
    2021-01-15 17:35

    This situation caused of output channel of sq function is not buffered. So sq is waiting until next function will read from output, but if sq is not async, it will not happen (Playground link):

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var wg sync.WaitGroup
    
    func main() {
        numsCh := gen(3, 4)
        sqCh := sq(numsCh) // if there is no sq in body - we are locked here until input channel will be closed
        result := sq(sqCh) // but if output channel is not buffered, so `sq` is locked, until next function will read from output channel
    
        for n := range result {
            fmt.Println(n)
        }
        fmt.Println("Process completed")
    }
    
    func gen(nums ...int) <-chan int {
        out := make(chan int)
        go func() {
            for _, n := range nums {
                out <- n
            }
            close(out)
        }()
        return out
    }
    
    func sq(in <-chan int) <-chan int {
        out := make(chan int, 100)
        for n := range in {
            out <- n * n
        }
        close(out)
        return out
    }
    

提交回复
热议问题