golang源码解析之chan
导语:在go语言中,chan 和 goroutine 是其并发模型CSP最重要体现,本文将基于1.14版本,深入源码,尽可能详细分析其内部实现原理。
一、为什么要使用chan
在并发线程中通信一般来说有两种模型:共享内存和消息传递。
常见的共享内存方式涉及到数据竞争这些问题,引入到锁、原子操作来解决。而基于消息传递的方式保证了不会产生数据竞争状态。
其中,实现消息传递有两种常见的类型:基于channel的消息传递和基于actor的消息传递。
而golang,就是基于channel的代表语言。erlang则是基于actor的代表语言。
在CSP(communicating sequential process)中,它将channel列为第一类对象,它不关注发送消息的实体,而是关注发送消息时使用的channel。golang则是基于这篇论文中的部分理论诞生的,也就是理论中的Process/channel:process和channel没有从属关系,process可以消费任意个channel,而channel也不关心具体是哪个process在使用它进行通信;process之间依据channel进行消息传递,形成一套有序阻塞和可预测的并发模型。对应到golang中,process就是goroutine,channel就是chan。
备注:CSP理论模型电子版链接:http://www.usingcsp.com/cspbook.pdf ,作者Tony Hoare
二、chan是怎样实现的
敲黑板:chan的实质是一个队列
如果你创建的是一个带缓冲的chan,chan就是一个循环队列,如果不带缓冲就是一个普通的队列。
在src/runtime/chan.go中,定义了一个结构体:hchan,还实现了一些方法:makechan、chansend、chanrecv、closechan,我们所使用的chan的最主要的功能,包括chan的创建,向chan写数据,读chan中的数据,关闭chan,就是围绕这个结构体和这几个方法实现的。我们接下来的内容,也主要围绕它们展开。
hchan
源码如下:
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
elemsize uint16
closed uint32
elemtype *_type // element type
sendx uint // send index
recvx uint // receive index
recvq waitq // list of recv waiters
sendq waitq // list of send waiters
// 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
}
qcount:buf数组中已经放入的元素个数
dataqsize:buf数组长度,创建时调用make指定
buf:buf 数组
elemsize:buf数组中每个元素的大小
closed:chan是否关闭, 0代表没有关闭
elemtype:chan中元素的类型
sendx:buf数组中以发送的索引位置,用以构造循环队列
recvx:buf数组中已接收的索引位置,用以构造循环队列
recvq:等待接收的goroutine,当chan中buf无数据并且无sendq时但有goroutine等待消费时会产生,实质是包含goroutine及有关信息的sudog,多个recvq会形成链表,依然是FIFO的标准队列
sendq:等待发送的goroutine,当chan中buf数据写满时但仍然有goroutine等待写入时会产生,实质是包含goroutine及有关信息的sudog,多个sendq会形成链表,依然是FIFO的标准队列。
lock:锁,用以保证chan中数据的顺序通信
makechan
源码如下:
func makechan(t *chantype, size int) *hchan {
elem := t.elem
// compiler checks this but be safe. 校验数据类型大小,大于1<<16(65536)异常
if elem.size >= 1<<16 {
throw("makechan: invalid channel element type")
}
//内存对齐(多平台兼容,降低维度提高速度,减少内存消耗),大于最大内次8字节时异常
if hchanSize%maxAlign != 0 || elem.align > maxAlign {
throw("makechan: bad alignment")
}
//判断所需空间是否大于堆可分配的最大内存
mem, overflow := math.MulUintptr(elem.size, uintptr(size))
if overflow || mem > maxAlloc-hchanSize || size < 0 {
panic(plainError("makechan: size out of range"))
}
// Hchan does not contain pointers interesting for GC when elements stored in buf do not contain pointers.
// buf points into the same allocation, elemtype is persistent.
// SudoG's are referenced from their owning thread so they can't be collected.
// TODO(dvyukov,rlh): Rethink when collector can move allocated objects.
var c *hchan
switch {
//size为0,分配hchan结构体空间
case mem == 0:
// Queue or element size is zero.
c = (*hchan)(mallocgc(hchanSize, nil, true))
// Race detector uses this location for synchronization.
c.buf = c.raceaddr()
//不包括指针,分配连续地址空间,包括hchan结构体+数据,将申请下来的地址首地址赋值给buf,便于GC回收,减小gc压力
case elem.ptrdata == 0:
// Elements do not contain pointers.
// Allocate hchan and buf in one call.
c = (*hchan)(mallocgc(hchanSize+mem, nil, true))
c.buf = add(unsafe.Pointer(c), hchanSize)
//包括指针,buf单独分配空间
default:
// Elements contain pointers.
c = new(hchan)
c.buf = mallocgc(mem, elem, true)
}
c.elemsize = uint16(elem.size)
c.elemtype = elem
c.dataqsiz = uint(size)
if debugChan {
print("makechan: chan=", c, "; elemsize=", elem.size, "; dataqsiz=", size, "\n")
}
return c
}
注意:makechan 返回的是hchan指针,这也就是为什么chan是golang中的引用类型,传递的是指针而非值
chansend
源码如下:
func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
//检测chan是否为空,为空报错,所以往一个nil的chan中写数据,程序会异常退出报错
if c == nil {
//如果是非阻塞的,返回false,不会触发
if !block {
return false
}
//如果是阻塞的goroutine停止
gopark