问题
chan
怎么答
chan
举例
1. 写未初始化的 chan
package main
// 写未初始化的chan
func main() {
var c chan int
c <- 1
}
复制代码
// 输出结果
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send (nil chan)]:
main.main()
/Users/admin18/go/src/repos/main.go:6 +0x36
复制代码
chan send (nil chan)
2. 写读未初始化的 chan
package main
import "fmt"
// 读未初始化的chan
func main() {
var c chan int
num, ok := <-c
fmt.Printf("读chan的协程结束, num=%v, ok=%v\n", num, ok)
}
复制代码
// 输出结果
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive (nil chan)]:
main.main()
/Users/admin18/go/src/repos/main.go:6 +0x46
复制代码
chan receive (nil chan)
多问一句
chanchan
1. 对于写的情况
//在 src/runtime/chan.go中
func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
if c == nil {
// 不能阻塞,直接返回 false,表示未发送成功
if !block {
return false
}
gopark(nil, nil, waitReasonChanSendNilChan, traceEvGoStop, 2)
throw("unreachable")
}
// 省略其他逻辑
}
复制代码
channilfalsechanchangopark(nil, nil, waitReasonChanSendNilChan, traceEvGoStop, 2)throw(s string)waitReasonChanSendNilChan"chan send (nil chan)"
2. 对于读的情况
//在 src/runtime/chan.go中
func chanrecv(c *hchan, ep unsafe.Pointer, block bool) (selected, received bool) {
//省略逻辑...
if c == nil {
if !block {
return
}
gopark(nil, nil, waitReasonChanReceiveNilChan, traceEvGoStop, 2)
throw("unreachable")
}
//省略逻辑...
}
复制代码
channilfalsechanchangopark(nil, nil, waitReasonChanReceiveNilChan, traceEvGoStop, 2)throw(s string)waitReasonChanReceiveNilChan"chan receive (nil chan)"
文章推荐:
如果你想每天学习一个知识点?
本文使用 mdnice 排版