美文网首页
【源码】Go 中 sync.Pool

【源码】Go 中 sync.Pool

作者: iceinto | 来源:发表于2022-01-06 10:18 被阅读0次

    sync.Pool

    介绍

    Pool是一个可以分别存取的临时对象的集合。

    Pool中保存的任何item都可能随时不做通告的释放掉。如果Pool持有该对象的唯一引用,这个item就可能被回收。

    Pool可以安全的被多个线程同时使用。

    Pool的目的是缓存申请但未使用的item用于之后的重用,以减轻GC的压力。也就是说,让创建高效而线程安全的空闲列表更容易。但Pool并不适用于所有空闲列表。

    Pool的合理用法是用于管理一组静静的被多个独立并发线程共享并可能重用的临时item。Pool提供了让多个线程分摊内存申请消耗的方法。

    Pool的一个好例子在fmt包里。该Pool维护一个动态大小的临时输出缓存仓库。该仓库会在过载(许多线程活跃的打印时)增大,在沉寂时缩小。

    另一方面,管理着短寿命对象的空闲列表不适合使用Pool,因为这种情况下内存申请消耗不能很好的分配。这时应该由这些对象自己实现空闲列表。

    由来讨论

    Brad Fizpatrick曾建议在sync包⾥里里加⼊入⼀一个公开的Cache类 型。这个建议引发了了⼀一⻓长串串的讨论。Go 语⾔言应该在标准库⾥里里 提供⼀一个这个样⼦子的类型,还是应当将这个类型作为私下的实 现?这个实现应该真的释放内存么?如果释放,什什么时候释放? 这个类型应当叫做Cache,或者更更应该叫做Pool?

    如何解决GC负重的问题?

    Go 是⾃自动垃圾回收,减少了了程序员的负担;

    GC 是⼀一把双刃剑,给编程带来便便利利的同时也增加了了运⾏行行时开销,使⽤用不不当甚⾄至会严重影响程序的性能;

    ⾼高性能场景下:不不能任意产⽣生太多的垃圾(GC 负担重,影 响性能);

    重⽤用对象;

    Go 官⽅方团队认识到这个问题普遍存在,避免⼤大家重复造轮⼦子,就出了了⼀一个 Pool 包:它设计的⽬目的是⽤用来保存和复⽤用临时对象,以减少内存分配,降低 CG压⼒力力。

    https://echo.labstack.com/guide/routing

    Echo 的路路由使⽤用了了 sync pool 来重复利利⽤用内存并且⼏几乎达到了了零内存占⽤用。

    直接看源代码: github.com/labstack/echo

    // echo.go
    e.pool.New = func() interface{} {
        return e.NewContext(nil, nil)
    }
    
    // body_limit.go
    func limitedReaderPool(c BodyLimitConfig) sync.Pool {
        return sync.Pool{
            New: func() interface{} {
                return &limitedReader{BodyLimitConfig: c}
            },
        }
    }
    
    // logger.go
    config.pool = &sync.Pool{
        New: func() interface{} {
            return bytes.NewBuffer(make([]byte, 256))
        },
    }
    

    gin的context通过pool来get和put (gin.go),也就是使⽤用了了sync.Pool进⾏行行维护

    engine.pool.New = func() interface{} {
        return engine.allocateContext()
    }
    

    sync.Pool 源码

    在初始化的时候,就会把pool的清除函数注册到runtime中:

    func init() {
        runtime_registerPoolCleanup(poolCleanup)
    }
    
    

    结构体

    type Pool struct {
        noCopy noCopy
    
        local     unsafe.Pointer // local fixed-size per-P pool, actual type is [P]poolLocal
        localSize uintptr        // size of the local array
    
        // New optionally specifies a function to generate
        // a value when Get would otherwise return nil.
        // It may not be changed concurrently with calls to Get.
        New func() interface{}
    }
    
    

    Pool在Golang是全局唯一的,不能被复制,用noCopy来控制,具体的限制方式为:

    var poolRaceHash [128]uint64
    
    func poolRaceAddr(x interface{}) unsafe.Pointer {
        ptr := uintptr((*[2]unsafe.Pointer)(unsafe.Pointer(&x))[1])
        h := uint32((uint64(uint32(ptr)) * 0x85ebca6b) >> 16)
        return unsafe.Pointer(&poolRaceHash[h%uint32(len(poolRaceHash))])
    }
    
    

    poolLocal数组的大小即P的数量,也就是给每一个系统线程分配了一个poolLocal,而poolLocal类型中保存了真正的数据。poolLocal分为private和shared两个域来保存对象,因为poolLocal中的对象可能会被其他P偷走,private域保证这个P不会被偷光,至少保留一个对象供自己用。否则,如果这个P只剩一个对象,被偷走了,那么当它本身需要对象时又要从别的P偷回来,造成了不必要的开销。代码如下:

    // Local per-P Pool appendix.
    type poolLocalInternal struct {
        private interface{}   // Can be used only by the respective P.
        shared  []interface{} // Can be used by any P.
        Mutex                 // Protects shared.
    }
    
    type poolLocal struct {
        poolLocalInternal
    
        // Prevents false sharing on widespread platforms with
        // 128 mod (cache line size) = 0 .
        pad [128 - unsafe.Sizeof(poolLocalInternal{})%128]byte
    }
    
    

    先来看看将一个对象放入到 Pool 中:

    // Put adds x to the pool.
    func (p *Pool) Put(x interface{}) {
        if x == nil {
            return
        }
        if race.Enabled {
            if fastrand()%4 == 0 {
                // Randomly drop x on floor.
                return
            }
            race.ReleaseMerge(poolRaceAddr(x))
            race.Disable()
        }
        l := p.pin()
        if l.private == nil {
            l.private = x
            x = nil
        }
        runtime_procUnpin()
        if x != nil {
            l.Lock()
            l.shared = append(l.shared, x)
            l.Unlock()
        }
        if race.Enabled {
            race.Enable()
        }
    }
    
    

    从 Pool 中获取一个对象:

    func (p *Pool) Get() interface{} {
        if race.Enabled {
            race.Disable()
        }
        l := p.pin()
        x := l.private
        l.private = nil
        runtime_procUnpin()
        if x == nil {
            l.Lock()
            last := len(l.shared) - 1
            if last >= 0 {
                x = l.shared[last]
                l.shared = l.shared[:last]
            }
            l.Unlock()
            if x == nil {
                x = p.getSlow()
            }
        }
        if race.Enabled {
            race.Enable()
            if x != nil {
                race.Acquire(poolRaceAddr(x))
            }
        }
        if x == nil && p.New != nil {
            x = p.New()
        }
        return x
    }
    
    

    其他参考参考项目

    参考资料

    相关文章

      网友评论

          本文标题:【源码】Go 中 sync.Pool

          本文链接:https://www.haomeiwen.com/subject/ttblcrtx.html