golang method to determine whether chan channel is turned off

  • 2020-06-01 10:00:03
  • OfStack

This example shows how golang determines whether chan channel is turned off. I will share it with you for your reference as follows:

Some friends in the group asked how to tell whether chan is closed or not, because channel of close will not block and return the nil value of the type, which will lead to an endless loop

If you do not judge whether chan is turned off

Notice: the following code generates a dead loop

package main
import (
    "fmt"
)
func main() {
    c := make(chan int, 10)
    c <- 1
    c <- 2
    c <- 3
    close(c)
    for {
        fmt.Println(<-c)
    }
}

Determine if the short chan is turned off

package main
import (
    "fmt"
)
func main() {
    c := make(chan int, 10)
    c <- 1
    c <- 2
    c <- 3
    close(c)
    for {
        i, isClose := <-c
        if !isClose {
            fmt.Println("channel closed!")
            break
        }
        fmt.Println(i)
    }
}

I hope this article has been helpful to you in programming Go.


Related articles: