golang判断短chan channel是否关闭

2014-06-09 15:45  11078人阅读  评论 (0)

群里有朋友问,怎么判断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, ok := <-c
        if !ok {
            fmt.Println("channel closed!")
            break
        }
        fmt.Println(i)
    }
}
2017-06-15 20:40 weakish
if !isClose {
fmt.Println("channel closed!")

这里isClose从语法上说应该是isClosed,另外名称和语义完全反了,应该改成isOpen(或者像官方教程里一样写成ok
2017-06-20 13:36 dotcoo
@weakish 谢谢





豫ICP备09035262号-1