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

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

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

sync.Pool作用

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

兩個結(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是提供外部使用的對象,Pool有兩個重要的成員,local是一個poolLocal數(shù)組,localSize是工作線程的數(shù)量( runtime.GOMAXPROCS(0)),Pool為每個線程分配一個poolLocal對象

寫入和讀取

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

sync.Pool注意點

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

大規(guī)模Goroutine的瓶頸

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

原理和作用

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

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

您可能感興趣的文章:

相關(guān)文章

最新評論