Channel实现
数据结构
type hchan struct {
qcount uint // total data in the queue 队列中的所有数据数
dataqsiz uint // size of the circular queue 环形队列的大小
buf unsafe.Pointer // points to an array of dataqsiz elements 指向大小为 dataqsiz 的数组
elemsize uint16 //元素大小
closed uint32 //是否关闭
elemtype *_type // element type 元素类型
sendx uint // send index 发送索引
recvx uint // receive index 接收索引
recvq waitq // list of recv waiters recv 等待列表,即( <-ch )
sendq waitq // list of send waiters send 等待列表,即( ch<- )
// lock protects all fields in hchan, as well as several
// fields in sudogs blocked on this channel.
//
// Do not change another G's status while holding this lock
// (in particular, do not ready a G), as this can deadlock
// with stack shrinking.
lock mutex
}
- buf里存放channel数据,是一个环形队列
- elemtype是channel里存放的数据类型,这里和反射一样用type类型存储
- sendx,recvx是接收和发送的偏移
- recvq,sendq是和channel相关的协程队列创建channel
写channel
写空channel
写已关闭channel
写有等待者的channel
写有缓冲,无等待者的channel
写阻塞channel
读channel
读空channel
读已关闭且无数据channel
读有发送方的channel
无等待者,有buf
读buf为空的channel
关闭channel
最后更新于