【WIP】Golang 理解channel源码

这期介绍关于golang channel的内部工作原理,从源码入手结合资料介绍channel作为goroutine的通信机制创建,写入,读出的过程。文中截图均源自或改编自kavya的understanding channels. 需要基本的goroutine知识,以及channel使用方法为基础来理解。

一,channel数据结构

在golang语言设计中,goroutine可以独立并行的执行任务,channel负责goroutine之间的交互和同步。

channel内部由一个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     mutex
}

除了各种容量参数外,buf是一个指向在堆中初始化的内存的指针,代表一个存储元素的队列;

elemtype是我们初始化c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值