1. 首页
  2. 文章

golang判断短chan channel是否关闭

moxiaopeng ·

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

本文来自:博客园

感谢作者:moxiaopeng

查看原文:golang判断短chan channel是否关闭

更多评论
总之判断是否关闭就是看到是否能取嘛~~
#2

用户登录

没有账号?注册

今日阅读排行

    加载中

一周阅读排行

    加载中