From 5d76c3f75b8853d6fb47b2906d87ea77aa0efd6e Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Mon, 28 Jul 2025 02:37:45 +0000 Subject: [PATCH] Fix race condition in pill timer --- step10/main.go | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/step10/main.go b/step10/main.go index 94b7707..b348985 100644 --- a/step10/main.go +++ b/step10/main.go @@ -259,20 +259,30 @@ func updateGhosts(ghosts []*ghost, ghostStatus GhostStatus) { } var pillTimer *time.Timer +var pillCancel chan struct{} func processPill() { pillMx.Lock() + defer pillMx.Unlock() + updateGhosts(ghosts, GhostStatusBlue) - if pillTimer != nil { - pillTimer.Stop() + + if pillCancel != nil { + close(pillCancel) } - pillTimer = time.NewTimer(time.Second * cfg.PillDurationSecs) - pillMx.Unlock() - <-pillTimer.C - pillMx.Lock() - pillTimer.Stop() - updateGhosts(ghosts, GhostStatusNormal) - pillMx.Unlock() + pillCancel = make(chan struct{}) + timer := time.NewTimer(time.Second * cfg.PillDurationSecs) + + go func(cancel chan struct{}) { + select { + case <-timer.C: + pillMx.Lock() + defer pillMx.Unlock() + updateGhosts(ghosts, GhostStatusNormal) + case <-cancel: + // timer cancelled + } + }(pillCancel) } func drawDirection() string {