记账: Recorder Close 幂等防重复关闭
- main 的 defer Shutdown 与显式 Close 双调用导致停机 panic close of closed channel - 用 sync.Once 保证只关闭一次 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -18,6 +18,7 @@ type Recorder struct {
|
|||||||
ch chan *store.UsageLog
|
ch chan *store.UsageLog
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
closed chan struct{}
|
closed chan struct{}
|
||||||
|
once sync.Once // 保证 Close 只执行一次(main 的 defer Shutdown 与显式 Close 双调用)
|
||||||
}
|
}
|
||||||
|
|
||||||
const batchSize = 32
|
const batchSize = 32
|
||||||
@@ -45,9 +46,11 @@ func (r *Recorder) Record(l *store.UsageLog) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Recorder) Close() {
|
func (r *Recorder) Close() {
|
||||||
|
r.once.Do(func() {
|
||||||
close(r.closed)
|
close(r.closed)
|
||||||
r.wg.Wait()
|
r.wg.Wait()
|
||||||
close(r.ch)
|
close(r.ch)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Recorder) run() {
|
func (r *Recorder) run() {
|
||||||
|
|||||||
Reference in New Issue
Block a user