Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kyzyc opened this issue Nov 12, 2024 · 1 comment
Open

Comments

@kyzyc
Copy link

kyzyc commented Nov 12, 2024

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
Copy link
Author

kyzyc commented Nov 12, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant