image.png

结构体

  1. type hchan struct {
  2. qcount uint // total data in the queue
  3. dataqsiz uint // size of the circular queue
  4. buf unsafe.Pointer // points to an array of dataqsiz elements
  5. elemsize uint16
  6. closed uint32 //状态值 0未开启,1为关闭
  7. elemtype *_type // element type
  8. sendx uint // send index
  9. recvx uint // receive index
  10. recvq waitq // list of recv waiters 接收队列
  11. sendq waitq // list of send waiters 发送协程的链表
  12. // lock protects all fields in hchan, as well as several
  13. // fields in sudogs blocked on this channel.
  14. //
  15. // Do not change another G's status while holding this lock
  16. // (in particular, do not ready a G), as this can deadlock
  17. // with stack shrinking.
  18. lock mutex
  19. // 互斥锁并不是排队发送/接收数据
  20. // 互斥锁保护的hchan结构体本身
  21. // channel并不是无锁的
  22. }

image.png

发送数据的底层原理

image.png

image.png

直接发送image.png

image.png

放入缓存

image.png
image.png

休眠等待

image.png
image.png

总结

image.png