1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00
Files
go-mixed/pool/pool.go
2022-05-06 15:30:58 +08:00

47 lines
593 B
Go

package pool
type Pool[T any] interface {
Get() (o T)
Put(o T)
}
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:
}
}