Go小技巧(一)— 擷取channel屬性

來源:互聯網
上載者:User

概述

這裡一個介紹一個方法,可以在不取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}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.