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