mirror of
https://github.com/duanhf2012/origin.git
synced 2026-02-04 06:54:45 +08:00
用原子操作优化定时器多协程并发性能
This commit is contained in:
@@ -93,8 +93,9 @@ type Timer struct {
|
|||||||
//停止停时器
|
//停止停时器
|
||||||
func (timer *Timer) Stop(){
|
func (timer *Timer) Stop(){
|
||||||
//将关闭标志设为1关闭状态
|
//将关闭标志设为1关闭状态
|
||||||
atomic.StoreInt32(&timer.isClose,1)
|
if atomic.SwapInt32(&timer.isClose,1) == 0 {
|
||||||
chanStopTimer<-timer
|
chanStopTimer<-timer
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//定时器是否已经停止
|
//定时器是否已经停止
|
||||||
@@ -102,6 +103,17 @@ func (timer *Timer) IsStop() bool {
|
|||||||
return atomic.LoadInt32(&timer.isClose) != 0
|
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 {
|
type slots struct {
|
||||||
timer *Timer //定时器链表头
|
timer *Timer //定时器链表头
|
||||||
@@ -227,7 +239,10 @@ func ReleaseTimer(timer *Timer) {
|
|||||||
func (t *timeWheel) addTimer(timer *Timer) *Timer {
|
func (t *timeWheel) addTimer(timer *Timer) *Timer {
|
||||||
//1.计算到期时间ticks
|
//1.计算到期时间ticks
|
||||||
ticks := timer.expireTicks - t.currentTicks
|
ticks := timer.expireTicks - t.currentTicks
|
||||||
|
if ticks<=0 {
|
||||||
|
timer.doTimeout()
|
||||||
|
return timer
|
||||||
|
}
|
||||||
//2.for遍历通过ticks找到适合的轮子插入,从底轮子往高找
|
//2.for遍历通过ticks找到适合的轮子插入,从底轮子往高找
|
||||||
var slot *slots
|
var slot *slots
|
||||||
for wheelIndex,info := range t.wheelInfos {
|
for wheelIndex,info := range t.wheelInfos {
|
||||||
@@ -297,9 +312,7 @@ func (t *timeWheel) TickOneFrame(){
|
|||||||
if currTimer.IsStop() == true {
|
if currTimer.IsStop() == true {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
select {
|
currTimer.doTimeout()
|
||||||
case currTimer.C<-currTimer:
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//3.将timer全部清空处理
|
//3.将timer全部清空处理
|
||||||
@@ -349,9 +362,7 @@ func (t *timeWheel) cascade(wheelIndex int) {
|
|||||||
//如果到时,直接送到channel
|
//如果到时,直接送到channel
|
||||||
if currentTimer.expireTicks<= t.currentTicks {
|
if currentTimer.expireTicks<= t.currentTicks {
|
||||||
if currentTimer.IsStop() == false {
|
if currentTimer.IsStop() == false {
|
||||||
select {
|
currentTimer.doTimeout()
|
||||||
case currentTimer.C<-currentTimer:
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}else{//否则重新添加,会加到下一级轮中
|
}else{//否则重新添加,会加到下一级轮中
|
||||||
t.addTimer(currentTimer)
|
t.addTimer(currentTimer)
|
||||||
|
|||||||
Reference in New Issue
Block a user