Golang app using sync.WaitGroup & channels never exits

后端 未结 1 365
既然无缘
既然无缘 2021-01-06 02:23

I use sync.WaitGroup, defer wg.Close() and wg.Wait() to wait for my goroutines to complete.

The program do wait, but it never

相关标签:
1条回答
  • You're never closing the fetchedSymbols channel, so that range loop will never exit.

    One way to handle this is to use use the WaitGroup you already have to signal when to close the channel. Ranging over fetchedSymbols is enough to block the progress in main, and you don't need another channel or WaitGroup.

    ...
    go func() {
        wg.Wait()
        close(fetchedSymbols)
    }()
    
    for response := range fetchedSymbols {
        fmt.Println("fetched " + response)
    }
    
    ...
    
    0 讨论(0)
提交回复
热议问题