Breaking Out of a Select Statement When All Channels Are Closed
Question:
How can you efficiently loop over multiple independent goroutines that produce data through channels until all channels are closed and stop consuming when channels exhaust their output?
Answer:
Using a select statement typically consumes data from multiple channels, but determining when all channels have closed can be challenging. Here's a concise way to handle this:
for { select { case p, ok := <-mins: if !ok { // channel is closed mins = nil // set channel to nil } else { fmt.Println("Min:", p) } case p, ok := <-maxs: if !ok { maxs = nil } else { fmt.Println("Max:", p) } } if mins == nil && maxs == nil { break // exit loop when all channels are nil } }
The trick here is to set the closed channel to nil to avoid further selecting on it. This ensures that the select statement keeps running and checks the remaining open channels.
Advantages:
The above is the detailed content of How to Break Out of a Select Statement When All Channels Are Closed?. For more information, please follow other related articles on the PHP Chinese website!