Go Channel源码解读
“Don’t communicate by sharing memory, share memory by communicating.” 不要通过共享内存来通信,而要通过通信来共享内存。 channel 介绍 channel是Go语言内置的一个非常重要的feature,相比其他语言,channel为Go提供了goroutine之间通信的独特方式。它和Linux的管道很像,goroutine可以向可写的channel写入数据,也可以从channel中读取数据,还可以关闭channel。这篇文章结合Go的源码来分析channel的实现原理,包括channel的创建、读、写和关闭。 channel实现原理 hchan结构体 Go语言的channel本质上是一个带锁的等待队列的循环缓冲区队列,它的源码在runtime/chan.go中,其实就是一个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 timer *timer // timer feeding this chan 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结构体各成员的含义如下: ...