Maison > développement back-end > Golang > Comment quitter gracieusement une instruction Select lorsque tous les canaux se ferment ?

Comment quitter gracieusement une instruction Select lorsque tous les canaux se ferment ?

DDD
Libérer: 2024-11-15 13:31:03
original
928 Les gens l'ont consulté

How to Gracefully Exit a Select Statement When All Channels Close?

Escaping a Select Statement when Multiple Channels Close

When utilizing the select statement for concurrent input handling, it may be desirable to exit the loop when all input channels have closed. The presented code snippet attempts to use a default case to handle this scenario, but it is insufficient as it cannot guarantee accurate detection.

A more effective solution involves niling closed channels within the select statement. When a channel closes, it is assigned a nil value, indicating it is no longer eligible for selection. This approach ensures that the loop will continue only as long as there are active channels.

In essence, the modified code will look as follows:

for {
    var x, ok = <-ch1 // Receive from ch1
    fmt.Println("ch1", x, ok)
    if !ok {
        ch1 = nil // Nil closed channel
    }

    x, ok = <-ch2 // Receive from ch2
    fmt.Println("ch2", x, ok)
    if !ok {
        ch2 = nil // Nil closed channel
    }

    if ch1 == nil && ch2 == nil {
        break // Exit loop when all channels are nil
    }
}
Copier après la connexion

This solution elegantly handles channel closure detection without introducing performance concerns, ensuring a concise and efficient implementation. As the number of input channels increases, the niling approach remains straightforward, making it scalable for handling multiple inputs.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal