记一次close chan出的问题
在一次写代码的过程中,将一个chan给close掉之后,发现有的时候在读chan的select中会报错,当时很纳闷为什么呢?
于是我就写了一个验证,发现close后读chan肯定能读出来nil,当时就懵逼了,不应该close了就读出,应该阻塞呀。
ch := make(chan *MM, 3)
go func() {
for {
select {
case c, ok := <-ch:
if c == nil || !ok {
fmt.Println("error ", c, ok)
return
} else {
fmt.Println("ok", c.N)
}
}
}
}()
ch<-&MM{N: 4}
time.Sleep(3*time.Second)
close(ch)
time.Sleep(30*time.Second)
ok 4
error <nil> false
没有见识的我怎么也没想通,然后我就点开了close准备想看看他是什么操作的时候,我发现我太真是读书不认真啊!
// The close built-in function closes a channel, which must be either
// bidirectional or send-only. It should be executed only by the sender,
// never the receiver, and has the effect of shutting down the channel after
// the last sent value is received. After the last value has been received
// from a closed channel c, any receive from c will succeed without
// blocking, returning the zero value for the channel element. The form
// x, ok := <-c
// will also set ok to false for a closed channel.
func close(c chan<- Type)
看到这儿应该都明白了