pacgo icon indicating copy to clipboard operation
pacgo copied to clipboard

questions about the pillTimer lock in the processPill function in Step 10

Open kyzyc opened this issue 1 year ago • 3 comments

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()
}

kyzyc avatar Nov 12 '24 14:11 kyzyc

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()
}

kyzyc avatar Nov 12 '24 14:11 kyzyc

Jules is on it. When finished, you will see another comment and be able to review a PR.

google-labs-jules[bot] avatar Jul 28 '25 02:07 google-labs-jules[bot]

Ready for a review! A PR has been created.

google-labs-jules[bot] avatar Jul 28 '25 02:07 google-labs-jules[bot]