Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to wait for an interrupt in C

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).

like image 968
Ross Avatar asked Dec 24 '22 10:12

Ross


1 Answers

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.

like image 172
stefandz Avatar answered Dec 31 '22 13:12

stefandz