在 C 中等待中断的有效方法 [英] Efficient way to wait for an interrupt in C
问题描述
我在树莓派上使用 WiringPi.有了它,我分配了一个稍后调用的中断函数.我不知道在等待中断被调用时该怎么做.
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.
示例使用 (spinlock?) for (;;)
例如
Examples use a (spinlock?) for (;;)
e.g.
int main()
{
// register interrupt
wiringPiISR( 18, INT_EDGE_BOTH, &myInterrupt );
for (;;) {
// really?
}
return 0;
}
而且我注意到 sleep
也有效.无论睡眠如何,都会调用中断
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)?
来自其他语言,我原以为 for(;;)
会消耗资源.我想知道要做什么或要做什么的指示(线程等).
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).
推荐答案
我最近不得不这样做.我的理论是KISS.sleep
被定义为使用最少的资源 - 使用它意味着我不必关心线程.
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.
简单、可读且对原始 Raspberry Pi B 没有可测量的性能影响:
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;
}
请注意使用 UINT_MAX 来最小化 for 循环调用的次数 - 这假设 WiringPi 使用的无符号 32 位定时器延迟.
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.
这篇关于在 C 中等待中断的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!