github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/go/src/sync/pool.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package sync 6 7 import ( 8 "internal/race" 9 "runtime" 10 "sync/atomic" 11 "unsafe" 12 ) 13 14 // A Pool is a set of temporary objects that may be individually saved and 15 // retrieved. 16 // 一个临时对象集组成一个池,可单独保存和读取; 17 // 18 // Any item stored in the Pool may be removed automatically at any time without 19 // notification. If the Pool holds the only reference when this happens, the 20 // item might be deallocated. 21 // 缓存对象随时可能被无通知的清除掉, 缓存对象占用的资源会被释放掉, 22 // 23 // A Pool is safe for use by multiple goroutines simultaneously. 24 // 缓存池是协程安全的 25 // 26 // Pool's purpose is to cache allocated but unused items for later reuse, 27 // relieving pressure on the garbage collector. That is, it makes it easy to 28 // build efficient, thread-safe free lists. However, it is not suitable for all 29 // free lists. 30 // 缓存池的目的是缓存之后要在使用的分配对象, 减少GC回收压力 31 // 即, 更容易的建立有效的,线程安全的列表 32 // 但是并不适合所有需要缓存的列表 33 // 34 // An appropriate use of a Pool is to manage a group of temporary items 35 // silently shared among and potentially reused by concurrent independent 36 // clients of a package. Pool provides a way to amortize allocation overhead 37 // across many clients. 38 // 切当使用缓冲池的一个场景是管理一组可能在一个包独立并发中会重复使用到的临时对象 39 // 缓存池提供一种为客服端摊销分配开销的解决方法 40 // 41 // An example of good use of a Pool is in the fmt package, which maintains a 42 // dynamically-sized store of temporary output buffers. The store scales under 43 // load (when many goroutines are actively printing) and shrinks when 44 // quiescent. 45 // 一个使用Pool的好的示例, 是在fmt pkg中 维护了一个动态大小的临时输出缓存 46 // 这个存储随着goroutine中激活的printing调用可自动伸缩; 47 // 48 // On the other hand, a free list maintained as part of a short-lived object is 49 // not a suitable use for a Pool, since the overhead does not amortize well in 50 // that scenario. It is more efficient to have such objects implement their own 51 // free list. 52 // 另一个方面, 维护一个短期对象列表并不适合用Pool , 因为这种场景并没有很好的分摊分配开销; 53 // 这种场景更适合专门定制 54 // 55 // A Pool must not be copied after first use. 56 // 初次使用后不能复制,sync包大多跟并发控制相关,出于安全考虑(避免指针的复制使得指针污染不安全,误操作而使程序崩溃)不能复制 57 type Pool struct { 58 // noCopy 是 Golang 源码中禁止拷贝的检测方法 59 noCopy noCopy 60 // local 是个数组,长度为 P 的个数。其元素类型是 poolLocal 61 // 这里面存储着各个 P 对应的本地对象池。可以近似的看做 [P]poolLocal 62 local unsafe.Pointer // local fixed-size per-P pool, actual type is [P]poolLocal 63 // 代表 local 数组的长度。因为 P 可以在运行时通过调用 runtime.GOMAXPROCS 进行修改, 64 // 因此我们还是得通过 localSize 来对应 local 数组的长度 65 localSize uintptr // size of the local array 66 67 // victim 和 victimSize 代表上一轮清理前的对象池,其内容语义 local 和 localSize 一致 68 victim unsafe.Pointer // local from previous cycle 69 victimSize uintptr // size of victims array 70 71 // New optionally specifies a function to generate 72 // a value when Get would otherwise return nil. 73 // It may not be changed concurrently with calls to Get. 74 // 用户提供的创建对象的函数。这个选项也不是必需。当不填的时候,Get 有可能返回 nil 75 New func() interface{} 76 } 77 78 // private 私有变量。Get 和 Put 操作都会优先存取 private 变量, 79 // 如果 private 变量可以满足情况,则不再深入进行其他的复杂操作。 80 // Local per-P Pool appendix. 81 type poolLocalInternal struct { 82 private interface{} // Can be used only by the respective P. 83 // shared。其类型为 poolChain,从名字不难看出这个是链表结构,这个就是 P 的本地对象池 84 shared poolChain // Local P can pushHead/popHead; any P can popTail. 85 } 86 87 // 每个 P 都会有一个 poolLocal 的本地 88 type poolLocal struct { 89 poolLocalInternal 90 91 // Prevents false sharing on widespread platforms with 92 // 128 mod (cache line size) = 0 . 93 pad [128 - unsafe.Sizeof(poolLocalInternal{})%128]byte 94 } 95 96 // from runtime 97 func fastrand() uint32 98 99 var poolRaceHash [128]uint64 100 101 // poolRaceAddr returns an address to use as the synchronization point 102 // for race detector logic. We don't use the actual pointer stored in x 103 // directly, for fear of conflicting with other synchronization on that address. 104 // Instead, we hash the pointer to get an index into poolRaceHash. 105 // See discussion on golang.org/cl/31589. 106 func poolRaceAddr(x interface{}) unsafe.Pointer { 107 ptr := uintptr((*[2]unsafe.Pointer)(unsafe.Pointer(&x))[1]) 108 h := uint32((uint64(uint32(ptr)) * 0x85ebca6b) >> 16) 109 return unsafe.Pointer(&poolRaceHash[h%uint32(len(poolRaceHash))]) 110 } 111 112 // Put adds x to the pool. 113 func (p *Pool) Put(x interface{}) { 114 if x == nil { 115 return 116 } 117 if race.Enabled { 118 if fastrand()%4 == 0 { 119 // Randomly drop x on floor. 120 return 121 } 122 race.ReleaseMerge(poolRaceAddr(x)) 123 race.Disable() 124 } 125 l, _ := p.pin() 126 if l.private == nil { 127 l.private = x // 将x 设置为private 之后 x 置空 128 x = nil 129 } 130 // 如果没有设置private 那么x 会被push 到shared 131 if x != nil { 132 l.shared.pushHead(x) 133 } 134 // 可以充许抢占P 135 runtime_procUnpin() 136 if race.Enabled { 137 race.Enable() 138 } 139 } 140 141 // Get selects an arbitrary item from the Pool, removes it from the 142 // Pool, and returns it to the caller. 143 // Get may choose to ignore the pool and treat it as empty. 144 // Callers should not assume any relation between values passed to Put and 145 // the values returned by Get. 146 // 147 // If Get would otherwise return nil and p.New is non-nil, Get returns 148 // the result of calling p.New. 149 func (p *Pool) Get() interface{} { 150 if race.Enabled { 151 race.Disable() 152 } 153 l, pid := p.pin() 154 x := l.private 155 l.private = nil 156 if x == nil { 157 // Try to pop the head of the local shard. We prefer 158 // the head over the tail for temporal locality of 159 // reuse. 160 //尝试从本地poolChain 中取数据 161 x, _ = l.shared.popHead() 162 if x == nil { 163 // 如果没有取到 164 // 尝试从其它P的缓冲池窃取对象 165 x = p.getSlow(pid) 166 } 167 } 168 runtime_procUnpin() 169 if race.Enabled { 170 race.Enable() 171 if x != nil { 172 race.Acquire(poolRaceAddr(x)) 173 } 174 } 175 if x == nil && p.New != nil { 176 x = p.New() 177 } 178 return x 179 } 180 181 func (p *Pool) getSlow(pid int) interface{} { 182 // See the comment in pin regarding ordering of the loads. 183 size := runtime_LoadAcquintptr(&p.localSize) // load-acquire 184 locals := p.local // load-consume 185 // Try to steal one element from other procs. 186 for i := 0; i < int(size); i++ { 187 l := indexLocal(locals, (pid+i+1)%int(size)) 188 // 从其它poolChain 的尾部窃取数据,取到就返回 189 if x, _ := l.shared.popTail(); x != nil { 190 return x 191 } 192 } 193 194 // Try the victim cache. We do this after attempting to steal 195 // from all primary caches because we want objects in the 196 // victim cache to age out if at all possible. 197 // 如果上面都取不到数据 就重试从上一轮清理的缓存victim中查找 198 size = atomic.LoadUintptr(&p.victimSize) 199 if uintptr(pid) >= size { 200 return nil 201 } 202 locals = p.victim 203 l := indexLocal(locals, pid) 204 if x := l.private; x != nil { 205 l.private = nil 206 return x 207 } 208 for i := 0; i < int(size); i++ { 209 l := indexLocal(locals, (pid+i)%int(size)) 210 if x, _ := l.shared.popTail(); x != nil { 211 return x 212 } 213 } 214 215 // Mark the victim cache as empty for future gets don't bother 216 // with it. 217 atomic.StoreUintptr(&p.victimSize, 0) 218 219 return nil 220 } 221 222 // pin pins the current goroutine to P, disables preemption and 223 // returns poolLocal pool for the P and the P's id. 224 // Caller must call runtime_procUnpin() when done with the pool. 225 // 返回P对应的本地缓存池poolLocal 226 func (p *Pool) pin() (*poolLocal, int) { 227 // procPin 表示暂时不许P被抢占 228 pid := runtime_procPin() 229 // In pinSlow we store to local and then to localSize, here we load in opposite order. 230 // Since we've disabled preemption, GC cannot happen in between. 231 // Thus here we must observe local at least as large localSize. 232 // We can observe a newer/larger local, it is fine (we must observe its zero-initialized-ness). 233 s := runtime_LoadAcquintptr(&p.localSize) // load-acquire 234 l := p.local // load-consume 235 if uintptr(pid) < s { 236 return indexLocal(l, pid), pid 237 } 238 return p.pinSlow() 239 } 240 241 func (p *Pool) pinSlow() (*poolLocal, int) { 242 // Retry under the mutex. 243 // Can not lock the mutex while pinned. 244 runtime_procUnpin() 245 allPoolsMu.Lock() 246 defer allPoolsMu.Unlock() 247 pid := runtime_procPin() 248 // poolCleanup won't be called while we are pinned. 249 s := p.localSize 250 l := p.local 251 if uintptr(pid) < s { 252 return indexLocal(l, pid), pid 253 } 254 if p.local == nil { 255 allPools = append(allPools, p) 256 } 257 // If GOMAXPROCS changes between GCs, we re-allocate the array and lose the old one. 258 // 初始化local数组 259 size := runtime.GOMAXPROCS(0) 260 local := make([]poolLocal, size) 261 atomic.StorePointer(&p.local, unsafe.Pointer(&local[0])) // store-release 262 runtime_StoreReluintptr(&p.localSize, uintptr(size)) // store-release 263 return &local[pid], pid 264 } 265 266 func poolCleanup() { 267 // This function is called with the world stopped, at the beginning of a garbage collection. 268 // It must not allocate and probably should not call any runtime functions. 269 270 // Because the world is stopped, no pool user can be in a 271 // pinned section (in effect, this has all Ps pinned). 272 273 // Drop victim caches from all pools. 274 for _, p := range oldPools { 275 p.victim = nil 276 p.victimSize = 0 277 } 278 279 // Move primary cache to victim cache. 280 for _, p := range allPools { 281 p.victim = p.local 282 p.victimSize = p.localSize 283 p.local = nil 284 p.localSize = 0 285 } 286 287 // The pools with non-empty primary caches now have non-empty 288 // victim caches and no pools have primary caches. 289 oldPools, allPools = allPools, nil 290 } 291 292 var ( 293 allPoolsMu Mutex 294 295 // allPools is the set of pools that have non-empty primary 296 // caches. Protected by either 1) allPoolsMu and pinning or 2) 297 // STW. 298 allPools []*Pool 299 300 // oldPools is the set of pools that may have non-empty victim 301 // caches. Protected by STW. 302 oldPools []*Pool 303 ) 304 305 func init() { 306 runtime_registerPoolCleanup(poolCleanup) 307 } 308 309 func indexLocal(l unsafe.Pointer, i int) *poolLocal { 310 lp := unsafe.Pointer(uintptr(l) + uintptr(i)*unsafe.Sizeof(poolLocal{})) 311 return (*poolLocal)(lp) 312 } 313 314 // Implemented in runtime. 315 func runtime_registerPoolCleanup(cleanup func()) 316 func runtime_procPin() int 317 func runtime_procUnpin() 318 319 // The below are implemented in runtime/internal/atomic and the 320 // compiler also knows to intrinsify the symbol we linkname into this 321 // package. 322 323 //go:linkname runtime_LoadAcquintptr runtime/internal/atomic.LoadAcquintptr 324 func runtime_LoadAcquintptr(ptr *uintptr) uintptr 325 326 //go:linkname runtime_StoreReluintptr runtime/internal/atomic.StoreReluintptr 327 func runtime_StoreReluintptr(ptr *uintptr, val uintptr) uintptr