等待C中中断的有效方法 [英] Efficient way to wait for an interrupt in C
问题描述
我在树莓派上使用WiringPi。我给它分配了一个中断函数,稍后再调用。我不确定在等Interupt打电话时该怎么办。
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)?
来自其他语言,我会以为 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循环调用的次数-假设无符号的32位计时器延迟,这是WiringPi所使用的。
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屋!