概述
這裡一個介紹一個方法,可以在不取channel裡的資料的前提下,查看channel是否關閉,是否阻塞,緩衝大小,通道內當前緩衝資料量等。
在這裡需要瞭解一下golang的記憶體模型,然後通過指標取出相應的值。
channel的結構體在chan.go中:
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 //... 以下欄位沒有用上,先省略}
從上面可以看出,現在要從出取出:
qcount:queue裡的資料總數
dataqsiz:queue的最大長度
closed:是否關閉
實現
首先我們定義一個struct來與hchan對應。(因為hchan裡的欄位長度不定,qcount、dataqsiz都是uint還好說,主要是取closed中間隔了個unint16,所以這裡偷個懶)
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}
省略欄位這裡沒用到,所以直接去掉就行了,上面的屬性順序和類型要與原hchan必須保持一致。
這裡想把它通用化所以包成方法接收的會是個interface{},如裡channel給interface{}那它在golang底層會被解析成eface:
type eface struct { _type *_type data unsafe.Pointer}
所以先將指標定位到eface.data再將指向的資料空間轉為自訂的hchan:
i := (*[2]uintptr)(unsafe.Pointer(&c))h := (*hchan)(unsafe.Pointer(i[1]))
這時h中值已經注入了。
附錄
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}type ChanInfo struct { Closed bool // 是否關閉 Len uint // channel內資料量 Cap uint // channel容量 Block bool // 是否已經阻塞} func ChanStatus(c interface{}) (*ChanInfo, error) { v := reflect.ValueOf(c) if v.Type().Kind() != reflect.Chan { return nil, errors.New("type must be channel") } i := (*[2]uintptr)(unsafe.Pointer(&c)) h := (*hchan)(unsafe.Pointer(i[1])) return &ChanInfo{ Cap: h.dataqsiz, Len: h.qcount, Closed: h.closed == 1, Block: h.qcount >= h.dataqsiz, }, nil}