Go语言中的channel是实现goroutine间无锁通信的关键机制,他使得写多线程并发程序变得简单、灵活、触手可得。
Channel是Go中的一个核心类型,你可以把它看成一个管道,通过它并发核心单元就可以发送或者接收数据进行通讯(communication)。
它的操作符是箭头 <- 。
ch <- v // 发送值v到Channel ch中
v := <-ch // 从Channel ch中接收数据,并将数据赋值给v
channel结构
type hchan struct {
qcount uint // total data in the queue 队列中存在的个数
dataqsiz uint // size of the circular queue buffer大小 实现看起来是个循环数组
buf unsafe.Pointer // points to an array of dataqsiz elements 数组指针
elemsize uint16 //channel类型的大小
closed uint32 //channel是否关闭
elemtype *_type // element type //channel 类型
sendx uint // send index //发送index
recvx uint // receive index //接收index
recvq waitq // list of recv waiters //接收链表 即读channel的goroutine
sendq waitq // list of send waiters //发送链表 即写channel的goroutine
// 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
}
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
程序员编程交流QQ群:805358732
如果你想用Python开辟副业赚钱,但不熟悉爬虫与反爬虫技术,没有接单途径,也缺乏兼职经验
关注下方微信公众号:Python编程学习圈,获取价值999元全套Python入门到进阶的学习资料以及教程,还有Python技术交流群一起交流学习哦。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!