questions about the pillTimer lock in the processPill function in Step 10
In Step 10, if the first goroutine is blocking while waiting for data from the pillTimer.C channel, and a second goroutine enters and stops the previous pillTimer, the first goroutine will never receive data from the pillTimer.C channel and will remain blocked until the program terminates. Although this locking mechanism in Step 10 ensures functional correctness, I wonder if this situation is still somewhat unsatisfactory.
var pillTimer *time.Timer
var pillMx sync.Mutex
func processPill() {
pillMx.Lock()
updateGhosts(ghosts, GhostStatusBlue)
if pillTimer != nil {
pillTimer.Stop()
}
pillTimer = time.NewTimer(time.Second * time.Duration(cfg.PillDurationSecs))
pillMx.Unlock()
<-pillTimer.C
pillMx.Lock()
pillTimer.Stop()
updateGhosts(ghosts, GhostStatusNormal)
pillMx.Unlock()
}
I came up with a solution, although it may not be the most perfect one.
var pillPNumMx sync.Mutex
var pillPNum = 0 // the number of processPill goroutines
func processPill() {
pillPNumMx.Lock()
pillPNum++
if pillPNum == 1 {
updateGhosts(ghosts, GhostStatusBlue)
}
pillPNumMx.Unlock()
time.Sleep(time.Second * time.Duration(cfg.PillDurationSecs))
pillPNumMx.Lock()
pillPNum--
if pillPNum == 0 {
updateGhosts(ghosts, GhostStatusNormal)
}
pillPNumMx.Unlock()
}
Jules is on it. When finished, you will see another comment and be able to review a PR.
Ready for a review! A PR has been created.