Channel 是golang語言自身提供的一種非常重要的語言特性罪郊, 它是實現(xiàn)任務(wù)執(zhí)行隊列、 協(xié)程間消息傳遞尚洽、高并發(fā)框架的基礎(chǔ)悔橄。關(guān)于channel的用法的文章已經(jīng)很多, 本文從channel源碼的實現(xiàn)的角度腺毫, 討論一下其實現(xiàn)原理癣疟。
關(guān)于channel放在: src/runtime/chan.go
channel的關(guān)鍵的結(jié)構(gòu)體放在hchan里面, 它記錄了channel實現(xiàn)的關(guān)鍵信息拴曲。
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
}
創(chuàng)建channel
用法: ch := make(chan TYPE争舞, size int);
這里, type是channel里面?zhèn)鬟f的elem的類型;
size是channel緩存的大械种:
如果為1矩桂, 代表非緩沖的channel, 表明channel里面最多有一個elem床牧, 剩余的只能在channel外排隊等待荣回;
如果為0,
其實現(xiàn)代碼如下:
func makechan(t *chantype, size int) *hchan {
// Hchan does not contain pointers interesting for GC when elements stored in buf do not contain pointers.
// buf points into the same allocation, elemtype is persistent.
// SudoG’s are referenced from their owning thread so they can’t be collected.
// TODO(dvyukov,rlh): Rethink when collector can move allocated objects.
var c *hchan
switch {
case size == 0 || elem.size == 0:
// Queue or element size is zero.
c = (*hchan)(mallocgc(hchanSize, nil, true))
// Race detector uses this location for synchronization.
c.buf = unsafe.Pointer(c)
case elem.kind&kindNoPointers != 0:
// Elements do not contain pointers.
// Allocate hchan and buf in one call.
c = (*hchan)(mallocgc(hchanSize+uintptr(size)*elem.size, nil, true))
c.buf = add(unsafe.Pointer(c), hchanSize)
default:
// Elements contain pointers.
c = new(hchan)
c.buf = mallocgc(uintptr(size)*elem.size, elem, true)
}
c.elemsize = uint16(elem.size)
c.elemtype = elem
c.dataqsiz = uint(size)
if debugChan {
print("makechan: chan=", c, "; elemsize=", elem.size, "; elemalg=", elem.alg, "; dataqsiz=", size, "\n")
}
return c
}
寫入channel elem
用法: ch <- elem
channel是阻塞時的管道戈咳, 從channel讀取的時候心软,可能發(fā)生如下3種情況:
channel 已經(jīng)關(guān)閉壕吹, 發(fā)生panic;
從已經(jīng)收到的隊列內(nèi)讀取一個elem删铃;
從緩存隊列內(nèi)讀取elem耳贬;
lock(&c.lock)
if c.closed != 0 {
unlock(&c.lock)
panic(plainError("send on closed channel"))
}
if sg := c.recvq.dequeue(); sg != nil {
// Found a waiting receiver. We pass the value we want to send
// directly to the receiver, bypassing the channel buffer (if any).
send(c, sg, ep, func() { unlock(&c.lock) }, 3)
return true
}
if c.qcount < c.dataqsiz {
// Space is available in the channel buffer. Enqueue the element to send.
qp := chanbuf(c, c.sendx)
if raceenabled {
raceacquire(qp)
racerelease(qp)
}
typedmemmove(c.elemtype, qp, ep)
c.sendx++
if c.sendx == c.dataqsiz {
c.sendx = 0
}
c.qcount++
unlock(&c.lock)
return true
}
if !block {
unlock(&c.lock)
return false
}
從channel elem讀取elem
用法: elem, ok := <- ch
if !ok {
fmt.Println(“ch has been closed”)
}
3種可能返回值:
chan已經(jīng)被關(guān)閉, OK為false猎唁, elem為該類型的空值咒劲;
如果chan此時沒有值存在, 該讀取語句會一直等待直到有值诫隅;
如果chan此時有值腐魂, 讀取正確的值, ok為true逐纬;
代碼實現(xiàn):
// chanrecv receives on channel c and writes the received data to ep.
// ep may be nil, in which case received data is ignored.
// If block == false and no elements are available, returns (false, false).
// Otherwise, if c is closed, zeros *ep and returns (true, false).
// Otherwise, fills in *ep with an element and returns (true, true).
// A non-nil ep must point to the heap or the caller's stack.
func chanrecv(c *hchan, ep unsafe.Pointer, block bool) (selected, received bool) {
// 正常的channel讀取流程蛔屹, 直接讀取
if sg := c.sendq.dequeue(); sg != nil {
// Found a waiting sender. If buffer is size 0, receive value
// directly from sender. Otherwise, receive from head of queue
// and add sender's value to the tail of the queue (both map to
// the same buffer slot because the queue is full).
recv(c, sg, ep, func() { unlock(&c.lock) }, 3)
return true, true
}
// 從緩存的elem隊列讀取一個elem
if c.qcount > 0 {
// Receive directly from queue
qp := chanbuf(c, c.recvx)
if raceenabled {
raceacquire(qp)
racerelease(qp)
}
if ep != nil {
typedmemmove(c.elemtype, ep, qp)
}
typedmemclr(c.elemtype, qp)
c.recvx++
if c.recvx == c.dataqsiz {
c.recvx = 0
}
c.qcount--
unlock(&c.lock)
return true, true
}
// channel沒有可以讀取的elem, 更新channel內(nèi)部狀態(tài)豁生, 等待新的elem兔毒;
}
關(guān)閉channel
用法: close(ch)
作用: 關(guān)閉channel, 并將channel內(nèi)緩存的elem清除沛硅;
代碼實現(xiàn):
func closechan(c *hchan) {
var glist *g
// release all readers
for {
sg := c.recvq.dequeue()
gp := sg.g
gp.param = nil
gp.schedlink.set(glist)
glist = gp
}
// release all writers (they will panic)
for {
sg := c.sendq.dequeue()
sg.elem = nil
gp := sg.g
gp.param = nil
gp.schedlink.set(glist)
glist = gp
}
unlock(&c.lock)
// Ready all Gs now that we've dropped the channel lock.
for glist != nil {
gp := glist
glist = glist.schedlink.ptr()
gp.schedlink = 0
goready(gp, 3)
}
}
??????每天堅持學習1小時Go語言眼刃,大家加油,我是彬哥摇肌,下期見擂红!如果文章中不同觀點、意見請文章下留言或者關(guān)注下方訂閱號反饋围小!
社區(qū)交流群:221273219
Golang語言社區(qū)論壇 :
www.Golang.Ltd
LollipopGo游戲服務(wù)器地址:
https://github.com/Golangltd/LollipopGo
社區(qū)視頻課程課件GIT地址:
https://github.com/Golangltd/codeclass