You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
1.8 KiB
86 lines
1.8 KiB
// ------------------------------------------------------------------------
|
|
// Project atila
|
|
// Active Thing (activething.com) git.activething.com/go
|
|
//
|
|
// File name pool.go
|
|
// Created by DEV
|
|
// Modified 17/01/2024
|
|
//
|
|
// Copyright 2024 activething.com
|
|
// ------------------------------------------------------------------------
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
// ------------------------------------------------------------------------
|
|
|
|
package syncs
|
|
|
|
import (
|
|
"activething.com/go/gogo/core/opts"
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
type (
|
|
|
|
Pool[T any] struct {
|
|
PoolStats
|
|
|
|
inner sync.Pool
|
|
|
|
cap int32
|
|
len int32
|
|
|
|
createFn func() *T
|
|
}
|
|
)
|
|
|
|
func NewPool[T any](ops ...opts.OptionFnc[Pool[T]]) *Pool[T] {
|
|
return opts.Apply(&Pool[T]{}, ops...)
|
|
}
|
|
|
|
func (p *Pool[T]) Len() int32 { return atomic.LoadInt32(&p.len) }
|
|
|
|
func (p *Pool[T]) Cap() int32 { return atomic.LoadInt32(&p.cap) }
|
|
|
|
func (p *Pool[T]) Get() *T {
|
|
o := p.inner.Get()
|
|
if o != nil {
|
|
p.AddAcquired()
|
|
if p.Len() > 0 {
|
|
atomic.AddInt32(&p.len, -1)
|
|
}
|
|
return o.(*T)
|
|
}
|
|
if o = p.createFn(); o != nil {
|
|
p.AddCreated()
|
|
}
|
|
return o.(*T)
|
|
}
|
|
|
|
func (p *Pool[T]) Put(obj *T) {
|
|
if obj == nil {
|
|
return
|
|
}
|
|
c := p.Cap()
|
|
p.AddReleased()
|
|
if c == -1 || c >= p.Len() {
|
|
atomic.AddInt32(&p.len, 1)
|
|
p.inner.Put(obj)
|
|
}
|
|
}
|
|
|
|
func (p *Pool[T]) Empty() {
|
|
for p.Len() > 0 {
|
|
_ = p.Get()
|
|
}
|
|
}
|