【发布时间】:2010-09-14 03:37:49
【问题描述】:
与question 类似,我想在 C 中限制函数的执行时间——最好是微秒级精度。我想 C++ 异常可用于实现类似于this 的结果Python 解决方案。虽然并不理想,但这种方法在纯 C 语言中完全不可用。
那么,我想知道,在 Posix 系统上的 C 语言中,我如何在某个时间间隔之后中断函数的执行?对于相对简单的情况,silly business 工作得很好,但这会增加大量与问题解决方案正交的代码。假设我有一个这样的函数:
void boil(egg *e) {
while (true)
do_boil(e);
}
我想在一个鸡蛋上运行煮沸*,每 50μs 中断一次以检查是否执行以下操作:
egg *e = init_egg();
while (true) {
preempt_in(50, (void) (*boil), 1, e);
/* Now boil(e) is executed for 50μs,
then control flow is returned to the
statement prior to the call to preempt_in.
*/
if (e->cooked_val > 100)
break;
}
我意识到可以使用 pthread 来执行此操作,但我更感兴趣的是避免使用它们。我可以在 SIGALRM 处理程序中在 ucontext_t 之间切换,但 POSIX 标准指出 setcontext/swapcontext 的使用不能在信号处理程序中使用,事实上,我注意到 Linux 和 Solaris 之间的不同行为这样做时的系统。
这种效果有可能达到吗?如果是这样,以便携的方式?
【问题讨论】:
标签: c posix real-time portability preemption