go-zero/core/syncx/pool.go

109 lines
1.8 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"sync"
"time"
"github.com/zeromicro/go-zero/core/timex"
2020-07-26 17:09:05 +08:00
)
type (
2021-02-28 16:16:22 +08:00
// PoolOption defines the method to customize a Pool.
2020-07-26 17:09:05 +08:00
PoolOption func(*Pool)
node struct {
item any
2020-07-26 17:09:05 +08:00
next *node
lastUsed time.Duration
}
2021-02-28 16:16:22 +08:00
// A Pool is used to pool resources.
// The difference between sync.Pool is that:
2021-05-10 00:09:00 +08:00
// 1. the limit of the resources
2021-02-28 16:16:22 +08:00
// 2. max age of the resources can be set
// 3. the method to destroy resources can be customized
2020-07-26 17:09:05 +08:00
Pool struct {
limit int
created int
maxAge time.Duration
lock sync.Locker
cond *sync.Cond
head *node
create func() any
destroy func(any)
2020-07-26 17:09:05 +08:00
}
)
2021-02-28 16:16:22 +08:00
// NewPool returns a Pool.
func NewPool(n int, create func() any, destroy func(any), opts ...PoolOption) *Pool {
2020-07-26 17:09:05 +08:00
if n <= 0 {
panic("pool size can't be negative or zero")
}
lock := new(sync.Mutex)
pool := &Pool{
limit: n,
lock: lock,
cond: sync.NewCond(lock),
create: create,
destroy: destroy,
}
for _, opt := range opts {
opt(pool)
}
return pool
}
2021-05-10 00:09:00 +08:00
// Get gets a resource.
func (p *Pool) Get() any {
2020-07-26 17:09:05 +08:00
p.lock.Lock()
defer p.lock.Unlock()
for {
if p.head != nil {
head := p.head
p.head = head.next
if p.maxAge > 0 && head.lastUsed+p.maxAge < timex.Now() {
p.created--
p.destroy(head.item)
continue
} else {
return head.item
}
}
if p.created < p.limit {
p.created++
return p.create()
}
p.cond.Wait()
}
}
2021-02-28 16:16:22 +08:00
// Put puts a resource back.
func (p *Pool) Put(x any) {
2020-07-26 17:09:05 +08:00
if x == nil {
return
}
p.lock.Lock()
defer p.lock.Unlock()
p.head = &node{
item: x,
next: p.head,
lastUsed: timex.Now(),
}
p.cond.Signal()
}
2021-02-28 16:16:22 +08:00
// WithMaxAge returns a function to customize a Pool with given max age.
2020-07-26 17:09:05 +08:00
func WithMaxAge(duration time.Duration) PoolOption {
return func(pool *Pool) {
pool.maxAge = duration
}
}