对已经关闭的 chan 进行读写,会怎么样?为什么?


作者:ych

我们知道 go 关键字可以用来开启一个 goroutine 进行任务处理,但多个任务之间如果需要通信,就需要用到通道(channel)了。

一、Channel的定义

声明并初始化一个通道,可以使用 Go 语言的内建函数 make,同时指定该通道类型的元素类型,下面声明了一个 chan int 类型的 channel:

  1. ch := make(chan int)

二、Channel的操作

发送(写):发送操作包括了“复制元素值”和“放置副本到通道内部”这两个步骤。即:进入通道的并不是操作符右边的那个元素值,而是它的副本。

  1. ch := make(chan int)
  2. // write to channel
  3. ch <- x

接收(读):接收操作包含了“复制通道内的元素值”、“放置副本到接收方”、“删掉原值”三个步骤。

  1. ch := make(chan int)
  2. // read from channel
  3. x <- ch
  4. // another way to read
  5. x = <- ch

关闭:关闭 channel 会产生一个广播机制,所有向 channel 读取消息的 goroutine 都会收到消息。

  1. ch := make(chan int)
  2. close(ch)

从一个已关闭的 channel 中读取消息永远不会阻塞,并且会返回一个为 false 的 ok-idiom,可以用它来判断 channel 是否关闭:

  1. v, ok := <-ch

如果 ok 是false,表明接收的 v 是产生的零值,这个 channel 被关闭了或者为空。

三、Channel发送和接收操作的特点

一个通道相当于一个先进先出(FIFO)的队列:也就是说,通道中的各个元素值都是严格地按照发送的顺序排列的,先被发送通道的元素值一定会先被接收。

对于同一个通道,发送操作之间和接收操作之间是互斥的:同一时刻,对同一通道发送多个元素,直到这个元素值被完全复制进该通道之后,其他针对该通道的发送操作才可能被执行。接收也是如此。

发送操作和接收操作中,对元素值的处理是不可分割的:前面我们知道发送一个值到通道,是先复制值,再将该副本移动到通道内部,“不可分割”指的是发送操作要么还没复制元素值,要么已经复制完毕,绝不会出现只复制了一部分的情况。接收也是同理,在准备好元素值的副本之后,一定会删除掉通道中的原值,绝不会出现通道中仍有残留的情况。

发送操作和接收操作在完全完成之前会被阻塞:发送操作包括了“复制元素值”和“放置副本到通道内部”这两个步骤。在这两个步骤完全完成之前,发起这个发送操作的那句代码会一直阻塞在那里,在它之后的代码不会有执行的机会,直到阻塞解除。

四、Channel的类型

channel 分为不带缓存的 channel 和带缓存的 channel。

使用 make 声明一个通道类型变量时,除了指定通道的元素类型,还可以指定通道的容量,也就是通道最多可以缓存多少个元素值,当容量为 0 时,该通道为非缓冲通道,当容量大于 0 时,该通道为带有缓冲的通道。

  1. ch := make(chan int) //无缓冲的channel
  2. ch := make(chan int, 3) //带缓冲的channel

非缓冲通道和缓冲通道有着不同的数据传递方式:

非缓冲通道:无论是发送操作还是接收操作,一开始执行就会被阻塞,直到配对的操作也开始执行,才会继续传递。即:只有收发双方对接上了,数据才会被传递。数据直接从发送方复制到接收方。非缓冲通道传递数据的方式是同步的。

缓冲通道:如果通道已满,对它的所有发送操作都会被阻塞,直到通道中有元素值被接收走。反之,如果通道已空,那么对它的所有接收操作都会被阻塞,直到通道中有新的元素值出现。元素值会先从发送方复制到缓冲通道,之后再由缓冲通道复制给接收方。缓冲通道传递数据的方式是异步的。

五、Channel的源码学习

Channel的主要实现在src/runtime/chan.go中,go 版本为go version go1.14.6 darwin/amd64这里主要看chansend如何实现的。

  1. func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
  2. if c == nil {
  3. if !block {
  4. return false
  5. }
  6. gopark(nil, nil, waitReasonChanSendNilChan, traceEvGoStop, 2)
  7. throw("unreachable")
  8. }
  9. if debugChan {
  10. print("chansend: chan=", c, "\n")
  11. }
  12. if raceenabled {
  13. racereadpc(c.raceaddr(), callerpc, funcPC(chansend))
  14. }
  15. // Fast path: check for failed non-blocking operation without acquiring the lock.
  16. //
  17. // After observing that the channel is not closed, we observe that the channel is
  18. // not ready for sending. Each of these observations is a single word-sized read
  19. // (first c.closed and second c.recvq.first or c.qcount depending on kind of channel).
  20. // Because a closed channel cannot transition from 'ready for sending' to
  21. // 'not ready for sending', even if the channel is closed between the two observations,
  22. // they imply a moment between the two when the channel was both not yet closed
  23. // and not ready for sending. We behave as if we observed the channel at that moment,
  24. // and report that the send cannot proceed.
  25. //
  26. // It is okay if the reads are reordered here: if we observe that the channel is not
  27. // ready for sending and then observe that it is not closed, that implies that the
  28. // channel wasn't closed during the first observation.
  29. if !block && c.closed == 0 && ((c.dataqsiz == 0 && c.recvq.first == nil) ||
  30. (c.dataqsiz > 0 && c.qcount == c.dataqsiz)) {
  31. return false
  32. }
  33. var t0 int64
  34. if blockprofilerate > 0 {
  35. t0 = cputicks()
  36. }
  37. lock(&c.lock)
  38. if c.closed != 0 {
  39. unlock(&c.lock)
  40. panic(plainError("send on closed channel"))
  41. }
  42. if sg := c.recvq.dequeue(); sg != nil {
  43. // Found a waiting receiver. We pass the value we want to send
  44. // directly to the receiver, bypassing the channel buffer (if any).
  45. send(c, sg, ep, func() { unlock(&c.lock) }, 3)
  46. return true
  47. }
  48. if c.qcount < c.dataqsiz {
  49. // Space is available in the channel buffer. Enqueue the element to send.
  50. qp := chanbuf(c, c.sendx)
  51. if raceenabled {
  52. raceacquire(qp)
  53. racerelease(qp)
  54. }
  55. typedmemmove(c.elemtype, qp, ep)
  56. c.sendx++
  57. if c.sendx == c.dataqsiz {
  58. c.sendx = 0
  59. }
  60. c.qcount++
  61. unlock(&c.lock)
  62. return true
  63. }
  64. if !block {
  65. unlock(&c.lock)
  66. return false
  67. }
  68. // Block on the channel. Some receiver will complete our operation for us.
  69. gp := getg()
  70. mysg := acquireSudog()
  71. mysg.releasetime = 0
  72. if t0 != 0 {
  73. mysg.releasetime = -1
  74. }
  75. // No stack splits between assigning elem and enqueuing mysg
  76. // on gp.waiting where copystack can find it.
  77. mysg.elem = ep
  78. mysg.waitlink = nil
  79. mysg.g = gp
  80. mysg.isSelect = false
  81. mysg.c = c
  82. gp.waiting = mysg
  83. gp.param = nil
  84. c.sendq.enqueue(mysg)
  85. gopark(chanparkcommit, unsafe.Pointer(&c.lock), waitReasonChanSend, traceEvGoBlockSend, 2)
  86. // Ensure the value being sent is kept alive until the
  87. // receiver copies it out. The sudog has a pointer to the
  88. // stack object, but sudogs aren't considered as roots of the
  89. // stack tracer.
  90. KeepAlive(ep)
  91. // someone woke us up.
  92. if mysg != gp.waiting {
  93. throw("G waiting list is corrupted")
  94. }
  95. gp.waiting = nil
  96. gp.activeStackChans = false
  97. if gp.param == nil {
  98. if c.closed == 0 {
  99. throw("chansend: spurious wakeup")
  100. }
  101. panic(plainError("send on closed channel"))
  102. }
  103. gp.param = nil
  104. if mysg.releasetime > 0 {
  105. blockevent(mysg.releasetime-t0, 2)
  106. }
  107. mysg.c = nil
  108. releaseSudog(mysg)
  109. return true
  110. }

从代码中可以看到:

有 goroutine 阻塞在 channel recv 队列上,此时缓存队列为空,直接将消息发送给 reciever goroutine,只产生一次复制。
当 channel 缓存队列有剩余空间时,将数据放到队列里,等待接收,接收后总共产生两次复制。
当 channel 缓存队列已满时,将当前 goroutine 加入 send 队列并阻塞。
所以,开头的面试题就有了答案:

读:

读已经关闭的 chan,能一直读到内容,但是读到的内容根据通道内关闭前是否有元素而不同。

如果 chan 关闭前,buffer 内有元素还未读,会正确读到 chan 内的值,且返回的第二个 bool 值为 true;

如果 chan 关闭前,buffer 内有元素已经被读完,chan 内无值,返回 channel 元素的零值,第二个 bool 值为 false。

写:

写已经关闭的 chan 会 panic。

相关推荐

golang 中解析 tag 是怎么实现的?反射原理是什么?(中高级肯定会问,比较难,需要自己多去总结)
使用gorm不当出现too Many Connections的问题
uint 类型溢出问题
golang map 使用注意的点,是否并发安全?
讲讲 Go 的 select 底层数据结构和一些特性?(难点,没有项目经常可能说不清,面试一般会问你项目中怎么使用select)
golang orm框架 gorm
golang进行封包和拆包的完整解决方案
调用函数传入结构体时,应该传值还是指针? (Golang 都是传值)
go defer,多个 defer 的顺序,defer 在什么时机会修改返回值?
Golang 单引号,双引号,反引号的区别?
golang面试题
Golang表示枚举类型的详细讲解
讲讲 Go 的 defer 底层数据结构和一些特性?
Golang空结构体 struct{} 的使用
为 sync.WaitGroup 中Wait函数支持 WaitTimeout 功能.
昨天那个在for循环里append元素的同事,今天还在么?
golang并发题目测试
序列化协议
机器人坐标问题
交替打印数字和字母
数组和切片的区别 (基本必问)
复利计算 递归/非递归
for range 的时候它的地址会发生变化么?
实现阻塞读且并发安全的map
在 golang 协程和channel配合使用
讲讲 Go 的 slice 底层数据结构和一些特性?
写出以下逻辑,要求每秒钟调用一次proc并保证程序不退出?
高并发下的锁与map的读写
判断两个给定的字符串排序后是否一致
常见语法题目2
golang 实现一个负载均衡案例(随机,轮训)
字符串替换问题
七道语法找错题目
golang 中 make 和 new 的区别?(基本必问)
判断字符串中字符是否全都不同
基本数据结构和算法
常见语法题目1
操作系统基本原理
翻转字符串

评论区

版权所有:机遇屋在线 Copyright © 2021-2025 jiyuwu Co., Ltd.

鲁ICP备16042261号-1