You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言sync.Pool源码中P的含义是什么?

Understanding "per-P" and "P" in sync.Pool's poolLocalInternal Comments

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 the P that owns this poolLocalInternal instance. Only Goroutines running on that specific P can read or write to this field, and since a P only runs one Goroutine at a time (preemption aside), no lock is needed here. This is the fastest path for sync.Pool operations—when a Goroutine can grab an object from its own P's private storage.
  • shared []interface{}: This slice is a shared pool that any P (and thus any Goroutine) can access. Since multiple Goroutines from different Ps might try to read/write here, the embedded Mutex ensures safe concurrent access. This is the fallback when a Goroutine can't find an object in its own P'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:16:06