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

Make new example for thread-safe singleton pin access #100

Open
alex-astronomer opened this issue Nov 17, 2021 · 2 comments
Open

Make new example for thread-safe singleton pin access #100

alex-astronomer opened this issue Nov 17, 2021 · 2 comments

Comments

@alex-astronomer
Copy link

I've been testing my library that uses rppal's OutputPins and found that because the tests run in parallel there were issues when trying to create multiple output pins from the same pin number in the different tests. This made me realize that it would make more sense to treat the pin struct that contains the output pins as a singleton, and use Mutex in order to make this singleton thread safe for the tests. Does this sound like an anti-pattern? I got it to work pretty well. I'd love to make an example to show how this solution worked for me.

@alex-astronomer
Copy link
Author

Most useful when testing and there's going to be parallel processes or threads testing functions that need to write to pins.

@golemparts
Copy link
Owner

golemparts commented Nov 18, 2021

Thanks for opening this issue! There are multiple ways to share an OutputPin in a multi-threaded application. Which one is best depends on your specific use case.

In regular multi-threaded applications I prefer either limiting access to the OutputPin to a single thread, and use message passing to interact with the pin from other threads, or pass around Arc<Mutex<OutputPin>> clones, depending on the application structure and requirements.

Singletons are generally discouraged, but I'm not sure if I could come up with a better way of doing things given the circumstances. You're welcome to share an example in this thread for the benefit of other people searching for it, but as for the official usage examples, I'd rather not encourage the use of singletons.

Specifically for interacting with pins in tests you could choose to run the tests sequentially by specifying the --test-threads=1 flag (or build a custom test harness) so you don't have to worry about multi-threaded access to the same pin.

Your issue has actually given me some food for thought. Perhaps Gpio needs a blocking alternative to get that waits until the specified pin becomes available. That would eliminate the need for a singleton, and make parallel tests a lot easier to manage.

EDIT: It might make more sense to make get blocking until a pin becomes available, and add try_get which returns immediately.

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

No branches or pull requests

2 participants