breaking out of a select statement when all channels are closed

前端 未结 5 1371
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2021-01-30 01:16

    Close is nice in some situations, but not all. I wouldn't use it here. Instead I would just use a done channel:

    for n := 2; n > 0; {
        select {
        case p := <-mins:
            fmt.Println("Min:", p)  //consume output
        case p := <-maxs:
            fmt.Println("Max:", p)  //consume output
        case <-done:
            n--
        }
    }
    

    Complete working example at the playground: http://play.golang.org/p/Cqd3lg435y

提交回复
热议问题