github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/localpool/localpool.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package localpool 15 16 import ( 17 "runtime" 18 _ "unsafe" // required by go:linkname 19 ) 20 21 // LocalPool is an thread local object pool. 22 // It's similar to sync.Pool but has some difference 23 // - It can define the size of the pool. 24 // - It never get GCed. 25 type LocalPool struct { 26 sizePerProc int 27 slots []*slot 28 newFn func() interface{} 29 resetFn func(obj interface{}) 30 } 31 32 type slot struct { 33 objs []interface{} 34 getHit int 35 getMiss int 36 putHit int 37 putMiss int 38 } 39 40 // NewLocalPool creates a pool. 41 // The sizePerProc is pool size for each PROC, so total pool size is (GOMAXPROCS * sizePerProc) 42 // It can only be used when the GOMAXPROCS never change after the pool created. 43 // newFn is the function to create a new object. 44 // resetFn is the function called before put back to the pool, it can be nil. 45 func NewLocalPool(sizePerProc int, newFn func() interface{}, resetFn func(obj interface{})) *LocalPool { 46 slots := make([]*slot, runtime.GOMAXPROCS(0)) 47 for i := 0; i < len(slots); i++ { 48 slots[i] = &slot{ 49 objs: make([]interface{}, 0, sizePerProc), 50 } 51 } 52 return &LocalPool{ 53 sizePerProc: sizePerProc, 54 slots: slots, 55 newFn: newFn, 56 resetFn: resetFn, 57 } 58 } 59 60 //go:linkname procPin runtime.procPin 61 func procPin() int 62 63 //go:linkname procUnpin runtime.procUnpin 64 func procUnpin() int