Go Channel实例剖析
本文档主要通过实际例子,GO版本v1.16.6,结合Go channel的数据结构进行分析,hchan里面的参数是怎么变化的,同时解析一下hchan里面buf的读与写,queue是怎么运作的。想要了解Go Channel源码的可以看,我之前的博客《GO Channel源码分析》
本文大纲如下,会先分析流程,数据结构,最后再实例:
channel send流程图
channel read流程图
hchan.buf的读与写
hchan.recvq/sendq的读与写
channel send实例分析
channel recv实例分析
channel send

channel read

和channel send大同小异
hchan.buf读与写
channel的buf其实就是一个环形队列,channel send和recv,分别是对buf的write和read。write的时候就是把写入value的地址copy到buf中对应的缓存地址去。read就是把buf在源码中是通过chanbuf来计算出read和write的地址。
在hcan中,datasize,qcount,sendx和recvx就是用来操作buf的参数。datasize是buf的空间大小,qcount是存储元素的数量,sendx是写入时的地址下标,recvx是读取时的地址下标。

hchan.recvq/sendq的读与写
hchan里面的recvq和sendq就是一个先进先出的queue,enqueue和dequeue可以通过下面的例子看一下。

channel send实例分析
以,chan type为int,缓存大小为2
同一个颜色的就是一步

channel recv实例分析
接着上个例子的结果
