golang sync.Pool在1.14中的優化

本文基於golang 1.14 對sync.Pool進行分析;

sync.Pool在1.12中實現的原理簡述

參考 Golang 的 sync.Pool設計思路與原理,這篇文章基於1.12版本對golang的sync.Pool實現原理進行了分析。關於sync.Pool的使用場景、基本概念的理解可以參考前面的文章。

在1.12中sync.Pool的設計思路簡單總結一下:

  1. 將 G 和 P 綁定,設置與P綁定的M禁止搶佔以防止 G 被搶佔。在綁定期間,GC 無法清理緩存的對象。
  2. 每個p都有獨享的緩存隊列,當g進行sync.pool操作時,先找到所屬p的private,如果沒有對象可用,加鎖從 shared切片裏獲取數據。如果還沒有拿到緩存對象,那麼到其他P的poolLocal進行偷數據,如果偷不到,那麼就創建新對象。

1.12 sync.pool的源碼,可以發現sync.pool裏會有各種的鎖邏輯,從自己的shared拿數據加鎖。getSlow()偷其他P緩存,也是需要給每個p加鎖。put歸還緩存的時候,還是會mutex加一次鎖。

go mutex鎖的實現原理簡單說,他開始也是atomic cas自旋,默認是4次嘗試,當還沒有拿到鎖的時候進行waitqueue gopack休眠調度處理,等待其他協程釋放鎖時進行goready調度喚醒。

Go 1.13之後,Go 團隊對sync.Pool的鎖競爭這塊進行了很多優化,這裏還改變了shared的數據結構,以前的版本用切片做緩存,現在換成了poolChain雙端鏈表。這個雙端鏈表的設計很有意思,你看sync.pool源代碼會發現跟redis quicklist相似,都是鏈表加數組的設計。

1.14 Pool 數據結構

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

	victim     unsafe.Pointer // local from previous cycle
	victimSize uintptr        // size of victims 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 poolLocalInternal struct {
	private interface{} // Can be used only by the respective P.
	shared  poolChain   // Local P can pushHead/popHead; any P can popTail.
}

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.local 實際上是一個類型 [P]poolLocal 數組,數組長度是調度器中P的數量,也就是說每一個P有自己獨立的poolLocal。通過P.id來獲取每個P自己獨立的poolLocal。在poolLocal中有一個poolChain。

這裏我們先忽略其餘的機構,重點關注poolLocalInternal.shared 這個字段。poolChain是一個雙端隊列鏈,緩存對象。 1.12版本中對於這個字段的併發安全訪問是通過mutex加鎖實現的;1.14優化後通過poolChain(無鎖化)實現的。

這裏我們先重點分析一下poolChain 是怎麼實現併發無鎖編程的。

poolChain

type poolChain struct {
	// head is the poolDequeue to push to. This is only accessed
	// by the producer, so doesn't need to be synchronized.
	head *poolChainElt

	// tail is the poolDequeue to popTail from. This is accessed
	// by consumers, so reads and writes must be atomic.
	tail *poolChainElt
}

type poolChainElt struct {
	poolDequeue

	// next and prev link to the adjacent poolChainElts in this
	// poolChain.
	//
	// next is written atomically by the producer and read
	// atomically by the consumer. It only transitions from nil to
	// non-nil.
	//
	// prev is written atomically by the consumer and read
	// atomically by the producer. It only transitions from
	// non-nil to nil.
	next, prev *poolChainElt
}

poolChain是一個動態大小的雙向鏈接列表的雙端隊列。每個出站隊列的大小是前一個隊列的兩倍。也就是說poolChain裏面每個元素poolChainElt都是一個雙端隊列

head指向的poolChainElt,是用於Producer去Push元素的,不需要做同步處理。
tail指向的poolChainElt,是用於Consumer從tail去pop元素的,這裏的讀寫需要保證原子性。

簡單來說,poolChain是一個單Producer,多Consumer併發訪問的雙端隊列鏈。

對於poolChain中的每一個雙端隊列 poolChainElt,包含了雙端隊列實體poolDequeue 一起前後鏈接的指針。

poolChain 主要方法有:

popHead() (interface{}, bool);
pushHead(val interface{}) 

popTail() (interface{}, bool)

popHeadpushHead函數是給Producer調用的;popTail是給Consumer併發調用的。

poolChain.popHead()

前面我們說了,poolChain的head 指針的操作是單Producer的。

func (c *poolChain) popHead() (interface{}, bool) {
	d := c.head
	for d != nil {
		if val, ok := d.popHead(); ok {
			return val, ok
		}
		// There may still be unconsumed elements in the
		// previous dequeue, so try backing up.
		d = loadPoolChainElt(&d.prev)
	}
	return nil, false
}

poolChain要求,popHead函數只能被Producer調用。看一下邏輯:

  1. 獲取頭結點 head;
  2. 如果頭結點非空就從頭節點所代表的雙端隊列poolDequeue中調用popHead函數。注意這裏poolDequeuepopHead函數和poolChainpopHead函數並不一樣。poolDequeue是一個固定size的ring buffer。
  3. 如果從head中拿到了value,就直接返回;
  4. 如果從head中拿不到value,就從head.prev再次嘗試獲取;
  5. 最後都獲取不到,就返回nil。

poolChain.pushHead()

func (c *poolChain) pushHead(val interface{}) {
	d := c.head
	if d == nil {
		// Initialize the chain.
		const initSize = 8 // Must be a power of 2
		d = new(poolChainElt)
		d.vals = make([]eface, initSize)
		c.head = d
		storePoolChainElt(&c.tail, d)
	}

	if d.pushHead(val) {
		return
	}

	// The current dequeue is full. Allocate a new one of twice
	// the size.
	newSize := len(d.vals) * 2
	if newSize >= dequeueLimit {
		// Can't make it any bigger.
		newSize = dequeueLimit
	}

	d2 := &poolChainElt{prev: d}
	d2.vals = make([]eface, newSize)
	c.head = d2
	storePoolChainElt(&d.next, d2)
	d2.pushHead(val)
}

poolChain要求,pushHead函數同樣只能被Producer調用。看一下邏輯:

  1. 首先還是獲取頭結點 head;
  2. 如果頭結點爲空,需要初始化chain
    1. 創建poolChainElt 節點,作爲head, 當然也是tail。
    2. poolChainElt 其實也是固定size的雙端隊列poolDequeue,size必須是2的n次冪。
  3. 調用poolDequeuepushHead函數將 val push進head的雙端隊列poolDequeue
  4. 如果push失敗了,說明雙端隊列滿了,需要重新創建一個雙端隊列d2,新的雙端隊列的size是前一個雙端隊列size的2倍;
  5. 更新poolChain的head指向最新的雙端隊列,並且建立雙鏈關係;
  6. 然後將val push到最新的雙端隊列。

這裏需要注意一點的是head其實是指向最後chain中最後一個結點(poolDequeue),chain執行push操作是往最後一個節點push。 所以這裏的head的語義不是針對鏈表結構,而是針對隊列結構。

poolChain.popTail()

func (c *poolChain) popTail() (interface{}, bool) {
	d := loadPoolChainElt(&c.tail)
	if d == nil {
		return nil, false
	}

	for {
		// It's important that we load the next pointer
		// *before* popping the tail. In general, d may be
		// transiently empty, but if next is non-nil before
		// the pop and the pop fails, then d is permanently
		// empty, which is the only condition under which it's
		// safe to drop d from the chain.
		d2 := loadPoolChainElt(&d.next)

		if val, ok := d.popTail(); ok {
			return val, ok
		}

		if d2 == nil {
			// This is the only dequeue. It's empty right
			// now, but could be pushed to in the future.
			return nil, false
		}

		// The tail of the chain has been drained, so move on
		// to the next dequeue. Try to drop it from the chain
		// so the next pop doesn't have to look at the empty
		// dequeue again.
		if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.tail)), unsafe.Pointer(d), unsafe.Pointer(d2)) {
			// We won the race. Clear the prev pointer so
			// the garbage collector can collect the empty
			// dequeue and so popHead doesn't back up
			// further than necessary.
			storePoolChainElt(&d2.prev, nil)
		}
		d = d2
	}
}

poolChain要求,popTail函數能被任何P調用,也就是所有的P都是Consumer。這裏總結下,當前G所對應的P在Pool裏面是Producer角色,任何P都是Consumer角色。

popTail函數是併發調用的,所以需要特別注意。

  1. 首先需要原子的load chain的tail指向的雙端隊列d(poolDequeue);
  2. 如果d爲空,pool還是空,所以直接return nil
  3. 下面就是典型的無鎖原子化編程:進入一個for循環
    1. 首先就是獲取tail的next結點d2。這裏需要強調一下爲什麼需要在tail執行popTail之前先load tail 的next結點。
      1. tail有可能存在短暫性爲空的場景。比如head和tail實際指向同一個結點(雙端隊列)時候,可能tail爲空只是暫時的,因爲存在有線程往head push數據的情況。
      2. 如果因爲tail 執行popTail()時因爲tail爲空而失敗了,然後再load tail.next,發現 tail.next非空,再將tail原子切換到tail.next,這個時候就會出現錯誤了。假設tail和head指向同一個結點,在判斷tail是空之後,head往裏面插入了很多個數據,直接將tail結點打滿,然後head指向下一個結點了。這時候tail.next也非空了。然後就將tail更新到tail.next,就會導致丟數據了。
      3. 所以必須在:1)tail執行popTail之前tail.next是非空的,2)tail執行popTail時發現tail是空的。滿足這兩個條件才能說明tail是永久性是空的。也就是需要提前load tail.next指針。
    2. 如果從tail裏面pop數據成功,就直接返回val。
    3. 如果從tail裏面pop數據失敗,並且d2也是空,說明當前chain裏面只有一個結點,並且是空。直接返回nil
    4. 如果從tail裏面pop數據失敗並且d2非空,說明tail已經被drain乾淨了,原子的tail到tail.next,並清除雙向鏈表關係。
    5. 從d2開始新的一輪for循環。

上面的流程是典型的的無鎖併發編程。

poolDequeue

poolChain中每一個結點都是一個雙端隊列poolDequeue

poolDequeue是一個無鎖的、固定size的、單Producer、多Consumer的deque。只有一個Producer可以從head去push或則pop;多個Consumer可以從tail去pop。

數據結構

type poolDequeue struct {
	// 用高32位和低32位分別表示head和tail
	// head是下一個fill的slot的index;
	// tail是deque中最老的一個元素的index
	// 隊列中有效元素是[tail, head)
	headTail uint64

	vals []eface
}

type eface struct {
	typ, val unsafe.Pointer
}

這裏通過一個字段 headTail 來表示head和tail的index。headTail是8個字節64位。

  1. 高32位表示head;
  2. 低32位表示tail。
  3. head和tail自加溢出時是安全的。

vals是一個固定size的slice,其實也就是一個 ring buffer,size必須是2的次冪(爲了做位運算);

pack/unpack

一個字段 headTail 來表示head和tail的index,所以需要有具體的pack和unpack邏輯:

const dequeueBits = 32

func (d *poolDequeue) unpack(ptrs uint64) (head, tail uint32) {
	const mask = 1<<dequeueBits - 1
	head = uint32((ptrs >> dequeueBits) & mask)
	tail = uint32(ptrs & mask)
	return
}

func (d *poolDequeue) pack(head, tail uint32) uint64 {
	const mask = 1<<dequeueBits - 1
	return (uint64(head) << dequeueBits) |
		uint64(tail&mask)
}

pack:

  1. 首先拿到mask,這裏實際上就是 0xffffffff(2^32-1)
  2. head左移32位 | tail&0xffffffff 就可以得到head和tail pack之後的值。

unpack:

  1. 首先拿到mask,這裏實際上就是 0xffffffff(2^32-1)
  2. ptrs右移32位拿到高32位然後 & mask 就可以得到head;
  3. ptrs直接 & mask 就可以得到低32位,也就是tail。

poolDequeue.pushHead

pushHead 將val push到head指向的位置,如果deque滿了,就返回false。

func (d *poolDequeue) pushHead(val interface{}) bool {
	ptrs := atomic.LoadUint64(&d.headTail)
	head, tail := d.unpack(ptrs)
	if (tail+uint32(len(d.vals)))&(1<<dequeueBits-1) == head {
		// Queue is full.
		return false
	}
	slot := &d.vals[head&uint32(len(d.vals)-1)]

	// Check if the head slot has been released by popTail.
	typ := atomic.LoadPointer(&slot.typ)
	if typ != nil {
		// Another goroutine is still cleaning up the tail, so
		// the queue is actually still full.
		return false
	}

	// The head slot is free, so we own it.
	if val == nil {
		val = dequeueNil(nil)
	}
	*(*interface{})(unsafe.Pointer(slot)) = val

	// Increment head. This passes ownership of slot to popTail
	// and acts as a store barrier for writing the slot.
	atomic.AddUint64(&d.headTail, 1<<dequeueBits)
	return true
}

主要邏輯:

  1. 原子load head和tail,
  2. 如果tail + len(vals) == head 說明deque已經滿了。
  3. 拿到head在vals中index的slot
  4. 如果slot的type非空,說明該slot還沒有被popTail release,實際上deque還是滿的;所以直接return false;
  5. 更新val到slot的指針指向的值。
  6. 原子的自加head

需要注意的是,pushHead不是併發安全的,只能有一個Producer去執行;只有slot的的type指針爲空時候slot纔是空。

poolDequeue.popHead

popHead 將head指向的前一個位置彈出,如果deque是空,就返回false。

func (d *poolDequeue) popHead() (interface{}, bool) {
	var slot *eface
	for {
		ptrs := atomic.LoadUint64(&d.headTail)
		head, tail := d.unpack(ptrs)
		if tail == head {
			// Queue is empty.
			return nil, false
		}

		// Confirm tail and decrement head. We do this before
		// reading the value to take back ownership of this
		// slot.
		head--
		ptrs2 := d.pack(head, tail)
		if atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2) {
			// We successfully took back slot.
			slot = &d.vals[head&uint32(len(d.vals)-1)]
			break
		}
	}

	val := *(*interface{})(unsafe.Pointer(slot))
	if val == dequeueNil(nil) {
		val = nil
	}
	// Zero the slot. Unlike popTail, this isn't racing with
	// pushHead, so we don't need to be careful here.
	*slot = eface{}
	return val, true
}

主要邏輯:

  1. 由於從head前一個位置pop元素,可能會與tail位置pop衝突,所以不可避免的需要cas操作。所以最開始進入就是一個for循環;
  2. 原子load poolDequeue.headTail然後unpack拿到head和tail
  3. 如果head == tail,表示deque是空,直接return nil.
  4. head –
  5. 根據新的head和老的tail, 重新pack出ptrs2;
  6. 原子cas更新poolDequeue.headTailatomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2)
  7. 如果更新成功,就拿到head執行的slot,並獲取到實際的value,並return;
  8. 如果原子更新失敗了,重新進入for循環再次執行。

poolDequeue.popTail

這個函數是可以被Consumer併發訪問的。

func (d *poolDequeue) popTail() (interface{}, bool) {
	var slot *eface
	for {
		ptrs := atomic.LoadUint64(&d.headTail)
		head, tail := d.unpack(ptrs)
		if tail == head {
			// Queue is empty.
			return nil, false
		}

		// Confirm head and tail (for our speculative check
		// above) and increment tail. If this succeeds, then
		// we own the slot at tail.
		ptrs2 := d.pack(head, tail+1)
		if atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2) {
			// Success.
			slot = &d.vals[tail&uint32(len(d.vals)-1)]
			break
		}
	}

	// We now own slot.
	val := *(*interface{})(unsafe.Pointer(slot))
	if val == dequeueNil(nil) {
		val = nil
	}

	// Tell pushHead that we're done with this slot. Zeroing the
	// slot is also important so we don't leave behind references
	// that could keep this object live longer than necessary.
	//
	// We write to val first and then publish that we're done with
	// this slot by atomically writing to typ.
	slot.val = nil
	atomic.StorePointer(&slot.typ, nil)
	// At this point pushHead owns the slot.

	return val, true
}

主要邏輯:

  1. 併發訪問,所以與cas相關的for循環不可少;
  2. 原子load,拿到head和tail值;
  3. 將(tail+1)和head重新pack成ptrs2;
  4. CAS:atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2); 如果更新成功,就拿到vals[tail]t的指針。如果失敗就再次返回1的for循環。
  5. 拿到slot對應的val。
  6. 將slot的val和type都清爲nil, 告訴pushHead, slot我們已經使用完了,pushHead可以往裏面填充數據了。

數據結構總結

用一張圖完整描述sync.Pool的數據結構:
在這裏插入圖片描述
強調一點:

  1. head的操作只能是local P;
  2. tail的操作是任意P;

參考網上一張圖來看更加清晰:
在這裏插入圖片描述
Pool 並沒有直接使用 poolDequeue,因爲它是fixed size的,而 Pool 的大小是沒有限制的。因此,在 poolDequeue 之上包裝了一下,變成了一個 poolChainElt 的雙向鏈表,可以動態增長。

Pool.Put

func (p *Pool) Put(x interface{}) {
	if x == nil {
		return
	}

	l, _ := p.pin()
	if l.private == nil {
		l.private = x
		x = nil
	}
	if x != nil {
		l.shared.pushHead(x)
	}
	runtime_procUnpin()
}

func (p *Pool) pin() (*poolLocal, int) {
	pid := runtime_procPin()
	// In pinSlow we store to local and then to localSize, here we load in opposite order.
	// Since we've disabled preemption, GC cannot happen in between.
	// Thus here we must observe local at least as large localSize.
	// We can observe a newer/larger local, it is fine (we must observe its zero-initialized-ness).
	s := atomic.LoadUintptr(&p.localSize) // load-acquire
	l := p.local                          // load-consume
	if uintptr(pid) < s {
		return indexLocal(l, pid), pid
	}
	return p.pinSlow()
}

func (p *Pool) pinSlow() (*poolLocal, int) {
	// Retry under the mutex.
	// Can not lock the mutex while pinned.
	runtime_procUnpin()
	allPoolsMu.Lock()
	defer allPoolsMu.Unlock()
	pid := runtime_procPin()
	// poolCleanup won't be called while we are pinned.
	s := p.localSize
	l := p.local
	if uintptr(pid) < s {
		return indexLocal(l, pid), pid
	}
	if p.local == nil {
		allPools = append(allPools, p)
	}
	// If GOMAXPROCS changes between GCs, we re-allocate the array and lose the old one.
	size := runtime.GOMAXPROCS(0)
	local := make([]poolLocal, size)
	atomic.StorePointer(&p.local, unsafe.Pointer(&local[0])) // store-release
	atomic.StoreUintptr(&p.localSize, uintptr(size))         // store-release
	return &local[pid], pid
}

Put函數主要邏輯:

  1. 先調用p.pin() 函數,這個函數會將當前 goroutine與P綁定,並設置當前g不可被搶佔(也就不會出現多個協程併發讀寫當前P上綁定的數據);
    1. 在p.pin() 函數裏面還會check per P的[P]poolLocal數組是否發生了擴容(P 擴張)。
    2. 如果發生了擴容,需要調用pinSlow()來執行具體擴容。擴容獲取一個調度器全局大鎖allPoolsMu,然後根據當前最新的P的數量去執行新的擴容。這裏的成本很高,所以儘可能避免手動增加P的數量。
  2. 拿到per P的poolLocal後,優先將val put到private,如果private已經存在,就通過調用shared.pushHead(x) 塞到poolLocal裏面的無鎖雙端隊列的chain中。Put函數對於雙端隊列來說是作爲一個Producer角色,所以這裏的調用是無鎖的。
  3. 最後解除當前goroutine的禁止搶佔。

Pool.Get

func (p *Pool) Get() interface{} {
	l, pid := p.pin()
	x := l.private
	l.private = nil
	if x == nil {
		// Try to pop the head of the local shard. We prefer
		// the head over the tail for temporal locality of
		// reuse.
		x, _ = l.shared.popHead()
		if x == nil {
			x = p.getSlow(pid)
		}
	}
	runtime_procUnpin()
	if x == nil && p.New != nil {
		x = p.New()
	}
	return x
}

func (p *Pool) getSlow(pid int) interface{} {
	// See the comment in pin regarding ordering of the loads.
	size := atomic.LoadUintptr(&p.localSize) // load-acquire
	locals := p.local                        // load-consume
	// Try to steal one element from other procs.
	for i := 0; i < int(size); i++ {
		l := indexLocal(locals, (pid+i+1)%int(size))
		if x, _ := l.shared.popTail(); x != nil {
			return x
		}
	}

	// Try the victim cache. We do this after attempting to steal
	// from all primary caches because we want objects in the
	// victim cache to age out if at all possible.
	size = atomic.LoadUintptr(&p.victimSize)
	if uintptr(pid) >= size {
		return nil
	}
	locals = p.victim
	l := indexLocal(locals, pid)
	if x := l.private; x != nil {
		l.private = nil
		return x
	}
	for i := 0; i < int(size); i++ {
		l := indexLocal(locals, (pid+i)%int(size))
		if x, _ := l.shared.popTail(); x != nil {
			return x
		}
	}

	// Mark the victim cache as empty for future gets don't bother
	// with it.
	atomic.StoreUintptr(&p.victimSize, 0)

	return nil
}

Get函數主要邏輯:

  1. 設置當前 goroutine 禁止搶佔;
  2. 從 poolLocal的private取,如果private不爲空直接return;
  3. 從 poolLocal.shared這個雙端隊列chain裏面無鎖調用去取,如果取得到也直接return;
  4. 上面都去不到,調用getSlow(pid)去取
    1. 首先會通過 steal 算法,去別的P裏面的poolLocal去取,這裏的實現是無鎖的cas。如果能夠steal一個過來,就直接return;
    2. 如果steal不到,則從 victim 裏找,和 poolLocal 的邏輯類似。最後,實在沒找到,就把 victimSize 置 0,防止後來的“人”再到 victim 裏找。
  5. 最後還拿不到,就通過New函數來創建一個新的對象。

這裏是一個很明顯的多層級緩存優化 + GPM調度結合起來。

private -> shared -> steal from other P -> victim cache -> New

victim cache優化與GC

對於Pool來說並不能夠無上限的擴展,否則對象佔用內存太多了,會引起內存溢出。

幾乎所有的池技術中,都會在某個時刻清空或清除部分緩存對象,那麼在 Go 中何時清理未使用的對象呢?

這裏是使用GC。在pool.go裏面的init函數 會註冊清理函數:

func init() {
	runtime_registerPoolCleanup(poolCleanup)
}

// mgc.go
//go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
func sync_runtime_registerPoolCleanup(f func()) {
	poolcleanup = f
}

編譯器會把 runtime_registerPoolCleanup 函數調用鏈接到 mgc.go 裏面的 sync_runtime_registerPoolCleanup函數調用,實際上註冊到poolcleanup函數。整個調用鏈如下:

gcStart() -> clearpools() -> poolcleanup()

也就是每一輪GC開始都會執行pool的清除操作。

func poolCleanup() {
	// This function is called with the world stopped, at the beginning of a garbage collection.
	// It must not allocate and probably should not call any runtime functions.

	// Because the world is stopped, no pool user can be in a
	// pinned section (in effect, this has all Ps pinned).

	// Drop victim caches from all pools.
	for _, p := range oldPools {
		p.victim = nil
		p.victimSize = 0
	}

	// Move primary cache to victim cache.
	for _, p := range allPools {
		p.victim = p.local
		p.victimSize = p.localSize
		p.local = nil
		p.localSize = 0
	}

	// The pools with non-empty primary caches now have non-empty
	// victim caches and no pools have primary caches.
	oldPools, allPools = allPools, nil
}

poolCleanup 會在 STW 階段被調用。整體看起來,比較簡潔。主要是將 local 和 victim 作交換,這樣也就不致於讓 GC 把所有的 Pool 都清空了,有 victim 在“兜底”。

重點:如果 sync.Pool 的獲取、釋放速度穩定,那麼就不會有新的池對象進行分配。如果獲取的速度下降了,那麼對象可能會在兩個 GC 週期內被釋放,而不是以前的一個 GC 週期。

在Go1.13之前的poolCleanup比較粗暴,直接清空了所有 Pool 的 p.local 和poolLocal.shared。

通過兩者的對比發現,新版的實現相比 Go 1.13 之前,GC 的粒度拉大了,由於實際回收的時間線拉長,單位時間內 GC 的開銷減小。

所以 p.victim 的作用其實就是次級緩存。

sync.Pool 總結

  1. 關鍵思想是對象的複用,避免重複創建、銷燬。將暫時不用的對象緩存起來,待下次需要的時候直接使用,不用再次經過內存分配,複用對象的內存,減輕 GC 的壓力。
  2. sync.Pool 是協程安全的,使用起來非常方便。設置好 New 函數後,調用 Get 獲取,調用 Put 歸還對象。
  3. 不要對 Get 得到的對象有任何假設,默認Get到對象是一個空對象,Get之後手動初始化。
  4. 好的實踐是:Put操作執行前將對象“清空”,並且確保對象被Put進去之後不要有任何的指針引用再次使用,不然極大概率導致data race。
  5. 第三和第四也就是考慮清楚複用對象的生命週期
  6. Pool 裏對象的生命週期受 GC 影響,不適合於做連接池,因爲連接池需要自己管理對象的生命週期。
  7. Pool 不可以指定⼤⼩,⼤⼩只受制於 GC 臨界值。
  8. procPin 將 G 和 P 綁定,防止 G 被搶佔。在綁定期間,GC 無法清理緩存的對象。
  9. 在加入 victim 機制前,sync.Pool 裏對象的最⼤緩存時間是一個 GC 週期,當 GC 開始時,沒有被引⽤的對象都會被清理掉;加入 victim 機制後,最大緩存時間爲兩個 GC 週期。
  10. Victim Cache 本來是計算機架構裏面的一個概念,是 CPU 硬件處理緩存的一種技術,sync.Pool 引入的意圖在於降低 GC 壓力的同時提高命中率。
  11. sync.Pool 的最底層使用切片加鏈表來實現雙端隊列,並將緩存的對象存儲在切片中。
  12. sync.Pool 的設計理念,包括:無鎖、操作對象隔離、原子操作代替鎖、行爲隔離——鏈表、Victim Cache 降低 GC 開銷。

參考文檔:
理解Go 1.13中sync.Pool的設計與實現
golang新版如何優化sync.pool鎖競爭消耗?
深度解密 Go 語言之 sync.Pool

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章