1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00

对象池

This commit is contained in:
2022-03-27 10:20:29 +08:00
parent 2b79cf64ca
commit 0f1949f531
2 changed files with 95 additions and 0 deletions

41
pool/pool.go Normal file
View File

@ -0,0 +1,41 @@
package pool
type pool[T any] struct {
noCopy struct{}
c chan T
new func() T
}
func NewPool[T any](poolSize int) *pool[T] {
return &pool[T]{
c: make(chan T, poolSize),
}
}
func NewPoolWithNew[T any](poolSize int, f func() T) *pool[T] {
return &pool[T]{
c: make(chan T, poolSize),
new: f,
}
}
func (p *pool[T]) Get() (o T) {
select {
case o = <-p.c:
default:
if p.new != nil {
o = p.new()
} else {
o = *new(T)
}
}
return
}
func (p *pool[T]) Put(o T) {
select {
case p.c <- o:
default:
}
}