英文原文
实例:
func C1P1() {
var ch chan int
close(ch)
}
结果
panic: close of nil channel
goroutine 1 [running]:
panic(0x458300, 0xc82000a170)
/home/wdy/go/src/runtime/panic.go:464 +0x3e6
main.main()
/home/wdy/learn/program-learn/golang/learnchannel.go:27 +0x1e
exit status 2
实例:
func C1P2() {
ch := make(chan int, 0)
close(ch)
close(ch)
}
结果:
panic: close of closed channel
goroutine 1 [running]:
panic(0x458300, 0xc82000a170)
/home/wdy/go/src/runtime/panic.go:464 +0x3e6
main.main()
/home/wdy/learn/program-learn/golang/learnchannel.go:27 +0x4d
exit status 2
实例:
func C1P3() {
ch := make(chan int, 0)
close(ch)
ch <- 2
}
结果:
panic: send on closed channel
goroutine 1 [running]:
panic(0x458300, 0xc82000a170)
/home/wdy/go/src/runtime/panic.go:464 +0x3e6
main.main()
/home/wdy/learn/program-learn/golang/learnchannel.go:23 +0x6c
exit status 2
Last one sender to leave, turns off the lights, which can be controlled by a atomic int
注意如果需要把关闭通道作为一个控制信号告知其他goroutine没有更多数据的情况下,需要显示关闭。讨论
实例:
func C9A1() {
fmt.Println("C9A1")
var ch chan int
ch <- 2
}
结果:
C9A1
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send (nil chan)]:
main.C9A1()
/home/wdy/learn/program-learn/golang/learnchannel.go:27 +0xf9
main.main()
/home/wdy/learn/program-learn/golang/learnchannel.go:37 +0x14
exit status 2
发送:
func C9A2() {
fmt.Println("C9A2")
var ch chan int
<-ch
}
结果:
C9A2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive (nil chan)]:
main.C9A2()
/home/wdy/learn/program-learn/golang/learnchannel.go:33 +0xec
main.main()
/home/wdy/learn/program-learn/golang/learnchannel.go:38 +0x14
exit status 2
A3. 发送到关闭的channel会引起panic
A4. 从关闭的cannel读操作,会立刻返回数据0值。
之前一直在CSDN上写文章,后面会逐步转换到简书上,还请大家多多支持。