From d08da30b848fd3061f464ff3db3741071fd8e876 Mon Sep 17 00:00:00 2001 From: boyce Date: Tue, 27 Oct 2020 13:47:30 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=A8=E5=8E=9F=E5=AD=90=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=AE=9A=E6=97=B6=E5=99=A8=E5=A4=9A=E5=8D=8F?= =?UTF-8?q?=E7=A8=8B=E5=B9=B6=E5=8F=91=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/timewheel/timewheel.go | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/util/timewheel/timewheel.go b/util/timewheel/timewheel.go index 08236ce..54cefae 100644 --- a/util/timewheel/timewheel.go +++ b/util/timewheel/timewheel.go @@ -93,8 +93,9 @@ type Timer struct { //停止停时器 func (timer *Timer) Stop(){ //将关闭标志设为1关闭状态 - atomic.StoreInt32(&timer.isClose,1) - chanStopTimer<-timer + if atomic.SwapInt32(&timer.isClose,1) == 0 { + chanStopTimer<-timer + } } //定时器是否已经停止 @@ -102,6 +103,17 @@ func (timer *Timer) IsStop() bool { return atomic.LoadInt32(&timer.isClose) != 0 } +func (timer *Timer) doTimeout(){ + if atomic.SwapInt32(&timer.isClose,1) != 0 { + return + } + timer.prev = nil + timer.next = nil + select { + case timer.C <- timer: + } +} + //每个时间轮上的刻度 type slots struct { timer *Timer //定时器链表头 @@ -227,7 +239,10 @@ func ReleaseTimer(timer *Timer) { func (t *timeWheel) addTimer(timer *Timer) *Timer { //1.计算到期时间ticks ticks := timer.expireTicks - t.currentTicks - + if ticks<=0 { + timer.doTimeout() + return timer + } //2.for遍历通过ticks找到适合的轮子插入,从底轮子往高找 var slot *slots for wheelIndex,info := range t.wheelInfos { @@ -297,9 +312,7 @@ func (t *timeWheel) TickOneFrame(){ if currTimer.IsStop() == true { continue } - select { - case currTimer.C<-currTimer: - } + currTimer.doTimeout() } //3.将timer全部清空处理 @@ -349,9 +362,7 @@ func (t *timeWheel) cascade(wheelIndex int) { //如果到时,直接送到channel if currentTimer.expireTicks<= t.currentTicks { if currentTimer.IsStop() == false { - select { - case currentTimer.C<-currentTimer: - } + currentTimer.doTimeout() } }else{//否则重新添加,会加到下一级轮中 t.addTimer(currentTimer)