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

Possibility for nondeterministic behaviour due to race condition #2

Open
simonprickett opened this issue Jul 8, 2023 · 0 comments
Open
Assignees
Labels
bug Something isn't working

Comments

@simonprickett
Copy link
Owner

simonprickett commented Jul 8, 2023

Received by email:

Hello Simon.

I read your article. I’ve been using Go for quite a while, but am just starting a project using a Raspberry Pi. I enjoyed the article quite a bit.

I believe that there is a small problem with the code, however. There is a race condition when exiting the program. It is possible (but not likely) that the goroutine processing the SIGTERM could be interrupted just before the os.Exit().

If this happened due to a Sleep() ending, thus allowing the for loop in main() to run, possibly turning a LED on. When the for loop paused for another Sleep(), the SIGTERM goroutine would then be able to complete the exit – with the LED on.

Again, this is very unlikely – but possible.

If you are interested in solving this, there are a few ways. The key is that the exit and the LED hardware call need to be in the same goroutine.

One way would be to expand the SIGTERM goroutine to also do the all of the hardware calls to turn on/off LED’s. This would guarantee a clean exit. A second channel, along with a select statement, would be used to allow the main() for loop to make such requests, rather executing them itself.

Another way would be to do it all in one function, main(). A select statement could choose between the SIGTERM channel and a 1 second timer tick channel. It could then do either the exit or the LED control. Both of these could be function calls. The function for the second-by-second LED control could be a state machine, basing what it does on a counter (global, so it remains outside the function). A switch statement would handle all of the LED-change times, and the maximum count (reset the counter to 0). All of the non-interesting times would be ignored.

Regards,

John

Investigate/fix this and update the article here as needed: https://github.com/simonprickett/simonprickett.github.io/blob/master/_posts/2018-05-24-raspberry-pi-coding-in-go-traffic-lights.md

@simonprickett simonprickett added the bug Something isn't working label Jul 8, 2023
@simonprickett simonprickett self-assigned this Jul 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant