breaking out of a select statement when all channels are closed

前端 未结 5 1376
后悔当初
后悔当初 2021-01-30 00:48

I have two goroutines independently producing data, each sending it to a channel. In my main goroutine, I\'d like to consume each of these outputs as they come in, but don\'t ca

5条回答
  •  一个人的身影
    2021-01-30 01:13

    When I came across such a need I took the below approach:

    var wg sync.WaitGroup
    wg.Add(2)
    
    go func() {
      defer wg.Done()
      for p := range mins {
        fmt.Println("Min:", p) 
      }
    }()
    
    go func() {
      defer wg.Done()
      for p := range maxs {
        fmt.Println("Max:", p) 
      }
    }()
    
    wg.Wait()
    

    I know this is not with single for select loop, but in this case I feel this is more readable without 'if' condition.

提交回复
热议问题