Go channel的关闭与遍历

channel的关闭与遍历

channel 的关闭

  • 使用内置函数 close 可以关闭 channel, 当 channel 关闭后,就不能再向 channel 写数据了,但是仍然可以从该 channel 读取数据

func close

func close(c chan<- Type)
  • 内建函数close关闭信道,该通道必须为双向的或只发送的。它应当只由发送者执行,而不应由接收者执行,其效果是在最后发送的值被接收后停止该通道。
  • 在最后的值从已关闭的信道中被接收后,任何对其的接收操作都会无阻塞的成功。
  • 对于已关闭的信道,语句:
x, ok := <-c
  • 还会将ok置为false。

  • 案例演示:
intChan := make(chan int, 3)
intChan<- 100
intChan<- 200
close(intChan) // close
-- 这是不能够再写入数到channel
-- intChan<- 300
fmt.Println("okook~")
-- 当管道关闭后,读取数据是可以的
n1 := <-intChan
fmt.Println("n1=", n1)

channel 的遍历

  • channel 支持 for--range 的方式进行遍历,请注意两个细节
    • 在遍历时,如果 channel 没有关闭,则回出现 deadlock 的错误
    • 在遍历时,如果 channel 已经关闭,则会正常遍历数据,遍历完后,就会退出遍历
  • 案例演示
//遍历管道
intChan2 := make(chan int, 100)
for i := 0; i < 100; i++ {
	intChan2<- i * 2  //放入100个数据到管道
}
//遍历管道不能使用普通的 for 循环
// for i := 0; i < len(intChan2); i++ {
// }
//在遍历时,如果channel没有关闭,则会出现deadlock的错误
//在遍历时,如果channel已经关闭,则会正常遍历数据,遍历完后,就会退出遍历
close(intChan2)
for v := range intChan2 {
	fmt.Println("v=", v)
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值