Home > Backend Development > Golang > How to Break Out of a Select Statement When All Channels Are Closed?

How to Break Out of a Select Statement When All Channels Are Closed?

DDD
Release: 2024-11-15 20:41:03
Original
250 people have browsed it

How to Break Out of a Select Statement When All Channels Are Closed?

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
    }
}
Copy after login

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:

  • Efficiently handles multiple independent channels.
  • Avoids excessive conditional checks or timeouts.
  • Simple and concise implementation.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template