You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crate/synchelper/pool.go

35 lines
606 B
Go

package synchelper
import (
"sync"
)
// NewPool 初始化 Pool,
// newFn 是资源的构造函数,
// putCond 返回 true 时表示资源可以被放回 Pool 中.
func NewPool[T any](newFn func() any, putCond func(v T) bool) Pool[T] {
return Pool[T]{
pool: &sync.Pool{New: newFn},
putCond: putCond,
}
}
// Pool 是通用的资源池
type Pool[T any] struct {
pool *sync.Pool
putCond func(v T) bool
}
// Get 获取资源
func (pool Pool[T]) Get() T {
return pool.pool.Get().(T)
}
// Put 放回资源
func (pool Pool[T]) Put(v T) {
if !pool.putCond(v) {
return
}
pool.pool.Put(v)
}