Go语言sync.Pool源码中P的含义是什么?
Great question! This ties directly to Go's runtime scheduler model, which is key to understanding how sync.Pool achieves efficient object reuse. Let's break this down step by step:
What is "P"?
In Go's GMP scheduling model (Goroutine-Machine-Processor), P stands for Processor. Think of it as a "resource holder" that connects Goroutines (G) to operating system threads (M). Each P maintains its own local resources—like a queue of runnable Goroutines, memory allocation caches, and yes, the sync.Pool local storage we're looking at. The Go scheduler ensures that Goroutines run on an M bound to a P, so each Goroutine is associated with exactly one P at any given time.
What does "per-P" mean?
When the comment says "Local per-P Pool appendix", it means that every P in the Go runtime has its own dedicated poolLocalInternal instance. sync.Pool creates one of these for each P to minimize lock contention—since Goroutines on the same P can access their local pool storage without fighting over global locks most of the time.
Breaking down the field comments
Let's map this to the code you shared:
type poolLocalInternal struct { private interface{} // Can be used only by the respective P. shared []interface{} // Can be used by any P. Mutex // Protects shared. }
private interface{}: This field is strictly reserved for thePthat owns thispoolLocalInternalinstance. Only Goroutines running on that specificPcan read or write to this field, and since aPonly runs one Goroutine at a time (preemption aside), no lock is needed here. This is the fastest path forsync.Pooloperations—when a Goroutine can grab an object from its ownP's private storage.shared []interface{}: This slice is a shared pool that anyP(and thus any Goroutine) can access. Since multiple Goroutines from differentPs might try to read/write here, the embeddedMutexensures safe concurrent access. This is the fallback when a Goroutine can't find an object in its ownP's private storage.
Why this design?
By splitting storage into per-P private and shared sections, sync.Pool minimizes the need for global synchronization. Most operations hit the lock-free private field, and only cross-P operations (like stealing objects from another P's shared pool) require locking. This makes sync.Pool extremely efficient for high-concurrency workloads, which is exactly what it's designed for.
内容的提问来源于stack exchange,提问作者jack-nie

