I am using WiringPi on a raspberry pi. With it I assign an interrupt function which is called later. I'm not sure what to do when waiting for the interupt to be called.
Examples use a (spinlock?) for (;;)
e.g.
int main()
{
// register interrupt
wiringPiISR( 18, INT_EDGE_BOTH, &myInterrupt );
for (;;) {
// really?
}
return 0;
}
And I noticed that sleep
works too. The interrupt is called regardless of the sleep
int main()
{
// register interrupt
wiringPiISR( 18, INT_EDGE_BOTH, &myInterrupt );
for (;;) {
sleep(1000000);
}
return 0;
}
What is the best practise to keep the program running, using minimal resources (say if this were for a background demon)?
Coming from other languages, I would have thought for(;;)
would eat up resources. I would like to know what to do or pointers on what to do (threads etc).
I recently had to do exactly this. My theory was KISS. sleep
is written to use minimal resources by definition - and using it means I don't have to care about threads.
Simple, readable and no measurable performance hit on an original Raspberry Pi B:
int main()
{
// register interrupt
wiringPiISR( 18, INT_EDGE_BOTH, &myInterrupt );
for (;;) {
sleep(UINT_MAX);
}
return 0;
}
Note the use of UINT_MAX to minimise number of for loop calls - this assumes an unsigned 32-bit timer delay, which is what WiringPi uses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With