聊聊gost的ObjectPool

本文主要研究一下gost的ObjectPoolgit

ObjectPool

gost/bytes/bytes_buffer_pool.gogithub

// Pool is bytes.Buffer Pool
type ObjectPool struct {
    New  New
    pool sync.Pool
}

func NewObjectPool(n New) *ObjectPool {
    return &ObjectPool{New: n}
}

// take returns *bytes.Buffer from Pool
func (p *ObjectPool) Get() PoolObject {
    v := p.pool.Get()
    if v == nil {
        return p.New()
    }

    return v.(PoolObject)
}

// give returns *byes.Buffer to Pool
func (p *ObjectPool) Put(o PoolObject) {
    o.Reset()
    p.pool.Put(o)
}

// Pool object
type PoolObject interface {
    Reset()
}

type New func() PoolObject
ObjectPool定義了New及sync.Pool屬性,它提供了Get、Put方法,同時還有NewObjectPool工程方法;New是一個func,返回PoolObject;PoolObject接口定義了Reset方法

defaultPool

gost/bytes/bytes_buffer_pool.gogoogle

var (
    defaultPool *ObjectPool
)

func init() {
    defaultPool = NewObjectPool(func() PoolObject {
        return new(bytes.Buffer)
    })
}

// GetBytesBuffer returns bytes.Buffer from pool
func GetBytesBuffer() *bytes.Buffer {
    return defaultPool.Get().(*bytes.Buffer)
}

// PutIoBuffer returns IoBuffer to pool
func PutBytesBuffer(buf *bytes.Buffer) {
    defaultPool.Put(buf)
}
defaultPool建立的ObjectPool,其Reset方法爲new(bytes.Buffer),其GetBytesBuffer將defaultPool.Get()轉換爲 *bytes.Buffer類型

實例

gost/bytes/bytes_buffer_pool_test.gocode

func TestBytesBufferPool(t *testing.T) {
    buf := GetBytesBuffer()
    bytes := []byte{0x00, 0x01, 0x02, 0x03, 0x04}
    buf.Write(bytes)
    if buf.Len() != len(bytes) {
        t.Error("iobuffer len not match write bytes' size")
    }
    PutBytesBuffer(buf)
    //buf2 := GetBytesBuffer()
    // https://go-review.googlesource.com/c/go/+/162919/
    // before go 1.13, sync.Pool just reserves some objs before every gc and will be cleanup by gc.
    // after Go 1.13, maybe there are many reserved objs after gc.
    //if buf != buf2 {
    //    t.Errorf("buf pointer %p != buf2 pointer %p", buf, buf2)
    //}
}
這裏展現用GetBytesBuffer獲取buf,再經過PutBytesBuffer歸還buf

小結

gost的ObjectPool定義了New及sync.Pool屬性,它提供了Get、Put方法,同時還有NewObjectPool工程方法;New是一個func,返回PoolObject;PoolObject接口定義了Reset方法。接口

doc

相關文章
相關標籤/搜索