记一次close chan出的问题

 

记一次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)

看到这儿应该都明白了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值