上一部分主要写了锁,本篇主要介绍Channel
channel是Go中非常重要的一个数据类型,它和goroutine紧密相连,是Go的CSP并发模型的重要体现。
不要通过共享内存来通信,而应该通过通信来共享内存
1 2 3 4 5 6 7 8 9 10 |
package main import "fmt" func main() { c := make(chan int) go func() { c <- 1 // 向channel发送数据 }() x := <-c // 从channel中接收数据 fmt.Println(x) } |
1、通过make(chan int)创建一个int channel(可以在channel初始化时指定缓冲区的大小,例如make(chan int,2),不指定则默认为0)
2、在一个goroutine中,通过c<-1将数据发送到channel中,<-可以理解为数据的流动方向。
3、在主goroutine中通过x := <-c接收channel中的数据,并赋值给x。
既然goroutin和channel分别对应csp中的实体和媒介,goroutin之间都是通过chennel来传递数据,那么是如何保证并发安全的呢?
通过阅读源码可以发现,channel内部是使用Mutext互斥锁来保证的( 之前也有人提出CAS无锁Channel的实现,但因为无锁Channel在多核测试中的表现和没有满足FIFO的特性等原因,该提案目前是搁浅状态)关于无锁channel的讨论
channel的核心源码位于runtime包的chan.go中。
hchan 是 channel 在 golang 中的内部实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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 } |
hchan的所有属性大体可以分为3类
1、buffer相关属性,当channel中的缓冲区大小不为0时,buffer中存放了待接收的数据。
2、waitq相关属性,即recvq和sendq,可以理解为一个标准的FIFO队列,recvq是等待接收数据的goroutine,sendq是等待发送数据的goroutine。
3、其它,例如lock(互斥锁)、elemtype(元素类型)、closed(channel 是否关闭,== 0 代表未 closed)
hchan的所有行为,基本都是围绕buffer和waitq来实现的
1 2 3 4 |
type waitq struct { first *sudog last *sudog } |
waitq是一个双向链表,里面保存了goroutine。
buffer使用 ring buffer(环形缓冲区)实现
在hchan中,可以看到 recvx和sendx 两个属性,recvx即当前已发送的元素在队列当中的索引位置,sendx 即 当前已接收的元素在队列当中的索引位置。
从 recvx 到 sendx 之间的元素,表示已正常存放入 buffer 中的数据。
hchan中的lock就是一个互斥锁,channel在发送和接收数据前,都会先进行加锁,待逻辑完成后执行再解锁,来保证并发安全。