golang判断短chan channel是否关闭

 

群里有朋友问,怎么判断chan是否关闭,因为close的channel不会阻塞,并返回类型的nil值,会导致死循环.在这里写个例子记录一下,并且分享给大家

如果不判断chan是否关闭

Notice: 以下代码会产生死循环

package main

import (
    "fmt"
)

func main() {
    c := make(chan int, 10)
    c <- 1
    c <- 2
    c <- 3
    close(c)

    for {
        fmt.Println(<-c)
    }
}   

判断短chan是否关闭

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)
    }
}

原文:http://www.dotcoo.com/golang-channel-is-closed