欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Golang之sync.Pool對(duì)象池對(duì)象重用機(jī)制總結(jié)

 更新時(shí)間:2023年07月13日 08:25:39   作者:編程妲己  
這篇文章主要對(duì)Golang的sync.Pool對(duì)象池對(duì)象重用機(jī)制做了一個(gè)總結(jié),文中有相關(guān)的代碼示例和圖解,具有一定的參考價(jià)值,需要的朋友可以參考下

sync.Pool作用

對(duì)象重用機(jī)制,為了減少GC,sync.Pool是可伸縮的,并發(fā)安全的

兩個(gè)結(jié)構(gòu)體

type Pool struct {
    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{}
}
// Local per-P Pool appendix.
type poolLocal struct {
    private interface{}   // Can be used only by the respective P.
    shared  []interface{} // Can be used by any P.
    Mutex                 // Protects shared.
    pad     [128]byte     // Prevents false sharing.
}

Pool是提供外部使用的對(duì)象,Pool有兩個(gè)重要的成員,local是一個(gè)poolLocal數(shù)組,localSize是工作線(xiàn)程的數(shù)量( runtime.GOMAXPROCS(0)),Pool為每個(gè)線(xiàn)程分配一個(gè)poolLocal對(duì)象

寫(xiě)入和讀取

  • Pool.Get 先獲取當(dāng)前線(xiàn)程私有值(poolLocal.private)獲取
    否則則從共享列表(poolLocal.shared)獲取
    否則則從其他線(xiàn)程的共享列表獲取
    否則直接通過(guò)New()分配一個(gè)返回值
  • Pool.Put 當(dāng)前線(xiàn)程私有制為空,賦值給私有值
    否則追加到共享列表

sync.Pool注意點(diǎn)

臨時(shí)性,當(dāng)發(fā)生GC時(shí),Pool的對(duì)象會(huì)被清除,并且不會(huì)有通知
無(wú)狀態(tài),當(dāng)前線(xiàn)程中的PoolLocal.shared的對(duì)象可能會(huì)被其他線(xiàn)程偷走

大規(guī)模Goroutine的瓶頸

會(huì)對(duì)垃圾回收(gc)造成負(fù)擔(dān),需要頻繁的釋放內(nèi)存
雖然goroutine只分配2KB,但是大量gorotine會(huì)消耗完內(nèi)存,并且gc也是goroutine調(diào)用的

原理和作用

原理類(lèi)似是IO多路復(fù)用,就是盡可能復(fù)用,池化的核心優(yōu)勢(shì)就在于對(duì)goroutine的復(fù)用。此舉首先極大減輕了runtime調(diào)度goroutine的壓力,其次,便是降低了對(duì)內(nèi)存的消耗

到此這篇關(guān)于Golang之sync.Pool對(duì)象池對(duì)象重用機(jī)制總結(jié)的文章就介紹到這了,更多相關(guān)Golang sync.Pool對(duì)象重用機(jī)制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論