This commit is contained in:
风扇滑翔翼
2026-05-17 13:21:49 +00:00
committed by GitHub
parent 316bcd6343
commit b92aa0358a
+18 -11
View File
@@ -3,7 +3,6 @@ package signal
import ( import (
"context" "context"
"sync" "sync"
"sync/atomic"
"time" "time"
) )
@@ -12,24 +11,31 @@ type ActivityUpdater interface {
} }
type ActivityTimer struct { type ActivityTimer struct {
mu sync.Mutex mu sync.Mutex
timer atomic.Pointer[time.Timer] // timer will be nil if this timer is already finished
timer *time.Timer
timeout time.Duration timeout time.Duration
onTimeout func() onTimeout func()
} }
func (t *ActivityTimer) Update() { func (t *ActivityTimer) Update() {
t.mu.Lock() // someone already called Update or closing, just return
if !t.mu.TryLock() {
return
}
defer t.mu.Unlock() defer t.mu.Unlock()
if timer := t.timer.Load(); timer != nil { if t.timer != nil {
timer.Reset(t.timeout) t.timer.Reset(t.timeout)
} }
} }
func (t *ActivityTimer) finish() { func (t *ActivityTimer) finish() {
if timer := t.timer.Swap(nil); timer != nil { t.mu.Lock()
timer.Stop() defer t.mu.Unlock()
if t.timer != nil {
t.timer.Stop()
t.onTimeout() t.onTimeout()
t.timer = nil
} }
} }
@@ -41,9 +47,9 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
t.mu.Lock() t.mu.Lock()
defer t.mu.Unlock() defer t.mu.Unlock()
if timer := t.timer.Load(); timer != nil { if t.timer != nil {
t.timeout = timeout t.timeout = timeout
timer.Reset(timeout) t.timer.Reset(timeout)
} }
} }
@@ -52,10 +58,11 @@ func CancelAfterInactivity(ctx context.Context, cancel context.CancelFunc, timeo
timeout: timeout, timeout: timeout,
onTimeout: cancel, onTimeout: cancel,
} }
// strange situation
if timeout == 0 { if timeout == 0 {
cancel() cancel()
return activityTimer return activityTimer
} }
activityTimer.timer.Store(time.AfterFunc(timeout, activityTimer.finish)) activityTimer.timer = time.AfterFunc(timeout, activityTimer.finish)
return activityTimer return activityTimer
} }