gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/pool/sync-pool.go (about) 1 package pool 2 3 import ( 4 "gitee.com/sy_183/go-common/option" 5 "sync" 6 ) 7 8 type SyncPool[O any] struct { 9 p sync.Pool 10 newFn func(p *SyncPool[O]) O 11 syncLimiter 12 } 13 14 func NewSyncPool[O any](new func(p *SyncPool[O]) O, options ...option.AnyOption) *SyncPool[O] { 15 p := &SyncPool[O]{newFn: new} 16 p.p.New = p.new 17 for _, opt := range options { 18 opt.Apply(p) 19 } 20 return p 21 } 22 23 func ProvideSyncPool[O any](new func(p Pool[O]) O, options ...option.AnyOption) Pool[O] { 24 return NewSyncPool(func(p *SyncPool[O]) O { 25 return new(p) 26 }, options...) 27 } 28 29 func (p *SyncPool[O]) new() any { 30 return p.newFn(p) 31 } 32 33 func (p *SyncPool[O]) Get() (o O) { 34 if p.alloc() { 35 return p.p.Get().(O) 36 } 37 return 38 } 39 40 func (p *SyncPool[O]) Put(obj O) { 41 p.p.Put(obj) 42 p.release() 43 }