mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-17 16:12:42 +08:00
47 lines
593 B
Go
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:
|
|
}
|
|
}
|