1.chan資料結構


一個channel只能傳遞一種型別的值,型別資訊存盤在hchan資料結構中,
- elemtype代表型別,用于資料傳遞程序中的賦值;
- elemsize代表型別大小,用于在buf中定位元素位置,
一個channel同時僅允許被一個goroutine讀寫,為簡單起見,本章后續部分說明讀寫程序時不再涉及加鎖和解鎖,
2.創建Chan
創建channel的程序實際上是初始化hchan結構,其中型別資訊和緩沖區長度由make陳述句傳入,buf的大小則與元素大小和緩沖區長度共同決定,
makeChan原始碼如下:
func makechan(t *chantype, size int) *hchan {
elem := t.elem
// compiler checks this but be safe.
if elem.size >= 1<<16 {
throw("makechan: invalid channel element type")
}
if hchanSize%maxAlign != 0 || elem.align > maxAlign {
throw("makechan: bad alignment")
}
mem, overflow := math.MulUintptr(elem.size, uintptr(size))
if overflow || mem > maxAlloc-hchanSize || size < 0 {
panic(plainError("makechan: size out of range"))
}
// 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 {
// no buffer 的場景,這種 channel 可以看成 pipe;
case mem == 0:
// Queue or element size is zero.
c = (*hchan)(mallocgc(hchanSize, nil, true))
// Race detector uses this location for synchronization.
c.buf = c.raceaddr()
case elem.ptrdata =https://www.cnblogs.com/lisus2000/archive/2023/01/29/= 0:// channel 元素不含指標的場景,那么是分配出一個大記憶體塊;
// Elements do not contain pointers.
// Allocate hchan and buf in one call.
c = (*hchan)(mallocgc(hchanSize+mem, nil, true))
c.buf = add(unsafe.Pointer(c), hchanSize)
default:// 默認場景,hchan 結構體和 buffer 記憶體塊單獨分配;
// Elements contain pointers.
c = new(hchan)
c.buf = mallocgc(mem, elem, true)
}
// channel 元素大小,如果是 int,那么就是 8 位元組;
c.elemsize = uint16(elem.size)
// 元素型別,這樣就知道 channel 里面每個元素究竟是啥
c.elemtype = elem
c.dataqsiz = uint(size)
lockInit(&c.lock, lockRankHchan)
if debugChan {
print("makechan: chan=", c, "; elemsize=", elem.size, "; dataqsiz=", size, "\n")
}
return c
}
makeChan只會初始化四個引數:buf,elemsize,elemtype,dataqsize
channel發送的代碼決議如下:



channel接收資料的代碼如下:




轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542519.html
標籤:其他

