golang 在多协程之间交互,除了支持传统的通过共享数据来进行通信(公共数据加锁),更推崇通过通信来共享数据。所谓的通过通信来共享数据,借鉴于csp并发模型(两个独立的并发实体通过共享的通讯管道进行通信的并发模型),即通过共享的channel在多个goroutine之间传递数据,达到共享数据的需求。
这里主要谈谈channel是如何实现的,先看看源码:
type hchan struct {
qcount uint // 队列中的元素个数
dataqsiz uint // 循环队列的数据大小
buf unsafe.Pointer // 缓存数组指针
elemsize uint16
closed uint32
elemtype *_type // element type
sendx uint // 待发送的index
recvx uint // 待接收的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
}
type waitq struct {
first *sudog
last *sudog
}
注意&#