在 Go 语言中,chan 是 Goroutine 之间通信与同步的核心原语,其底层结构定义在 runtime/chan.go 的 hchan 结构体中。
一、hchan 核心字段
go
type hchan struct {
qcount uint // 当前环形队列中的元素个数
dataqsiz uint // 环形队列容量
buf unsafe.Pointer // 指向环形数组内存
sendx uint // 发送索引
recvx uint // 接收索引
sendq waitq // 阻塞的发送者队列
recvq waitq // 阻塞的接收者队列
}当缓冲区满时,发送方 Goroutine 会被封装为 sudog 挂入 sendq 并调用 gopark 让出 CPU;接收方消费数据后通过 goready 唤醒队首等待者。理解 hchan 有助于避免无缓冲 Channel 滥用导致的 Goroutine 泄漏。