fix: 修复 timer.Ticker 和 lockstep 包存在的内存泄漏问题

This commit is contained in:
kercylan98 2023-12-20 16:57:54 +08:00
parent 4d72e8cbcb
commit 508e30fb5b
4 changed files with 29 additions and 3 deletions

View File

@ -277,7 +277,7 @@ func (slf *Conn) Write(packet []byte, callback ...func(err error)) {
}
func (slf *Conn) init() {
if slf.server.ticker != nil {
if slf.server.ticker != nil && slf.server.connTickerSize > 0 {
if slf.server.tickerAutonomy {
slf.ticker = timer.GetTicker(slf.server.connTickerSize)
} else {
@ -335,6 +335,9 @@ func (slf *Conn) init() {
func (slf *Conn) Close(err ...error) {
slf.mu.Lock()
if slf.closed {
if slf.ticker != nil {
slf.ticker.Release()
}
slf.mu.Unlock()
return
}

View File

@ -123,6 +123,9 @@ func (slf *Lockstep[ClientID, Command]) StartBroadcast() {
return
}
slf.running = true
if slf.ticker == nil {
slf.ticker = timer.GetTicker(10)
}
slf.runningLock.Unlock()
slf.currentFrame = slf.initFrame
@ -175,7 +178,10 @@ func (slf *Lockstep[ClientID, Command]) StopBroadcast() {
slf.running = false
slf.runningLock.Unlock()
slf.ticker.StopTimer("lockstep")
if slf.ticker != nil {
slf.ticker.Release()
}
slf.ticker = nil
slf.OnLockstepStoppedEvent()

View File

@ -38,7 +38,11 @@ func (slf *Ticker) Release() {
}
slf.lock.Unlock()
slf.timer.tickers = append(slf.timer.tickers, slf)
if len(slf.timer.tickers) < tickerPoolSize {
slf.timer.tickers = append(slf.timer.tickers, slf)
} else {
slf.wheel.Stop()
}
}
// StopTimer 停止特定名称的调度器

View File

@ -6,8 +6,21 @@ import (
"github.com/RussellLuo/timingwheel"
)
var tickerPoolSize = 96
var timer = new(Timer)
// SetTickerPoolSize 设置定时器池大小
// - 默认值为 96当定时器池中的定时器不足时会自动创建新的定时器当定时器释放时会将多余的定时器进行释放否则将放入定时器池中
func SetTickerPoolSize(size int) {
if size <= 0 {
panic("ticker pool size must be greater than 0")
}
timer.lock.Lock()
defer timer.lock.Unlock()
tickerPoolSize = size
}
func GetTicker(size int, options ...Option) *Ticker {
return timer.NewTicker(size, options...)
}