Skip to content

Commit 4d24510

Browse files
author
Sunil Thaha
authored
Merge pull request #2146 from sthaha/fix-race-condition
fix(monitor): race condition between timer and context cancelation
2 parents 02d572a + 99a271e commit 4d24510

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

internal/monitor/monitor.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,13 +175,20 @@ func (pm *PowerMonitor) scheduleNextCollection() {
175175
go func() {
176176
select {
177177
case <-timer:
178+
// Check if context is cancelled before doing any work to avoid a race condition
179+
// where the context is cancelled after the timer has expired
180+
if err := pm.collectionCtx.Err(); err != nil {
181+
pm.logger.Info("Collection loop terminated; context canceled", "reason", err)
182+
return
183+
}
184+
178185
if err := pm.synchronizedPowerRefresh(); err != nil {
179186
pm.logger.Error("Failed to collect power data", "error", err)
180187
}
181188
pm.scheduleNextCollection()
182189

183190
case <-pm.collectionCtx.Done():
184-
pm.logger.Info("Collection loop terminated")
191+
pm.logger.Info("Collection loop terminated", "reason", pm.collectionCtx.Err())
185192
return
186193
}
187194
}()

0 commit comments

Comments
 (0)