代码之家  ›  专栏  ›  技术社区  ›  troutwine

如何限制C/POSIX中函数的执行时间?

  •  2
  • troutwine  · 技术社区  · 15 年前

    类似于此 question 我想在C中限制函数的执行时间,最好是微秒级的精度。我想C++异常可以用来达到类似的结果。 this python解决方案。虽然这并不理想,但是这种方法在普通C语言中是完全不可用的。

    那么,我想知道,在POSIX系统上,在C语言的某个时间间隔之后,如何中断函数的执行?对于相对简单的情况 silly business 工作得很好,但这会在问题解决方案中添加大量正交的代码。假设我有一个这样的函数:

    void boil(egg *e) {
        while (true)
        do_boil(e);
    }
    

    我想在一个鸡蛋上运行run boil*,每隔50分钟中断一次检查,这样做:

    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;
    }
    

    我知道pthreads可以用来做这个,但是我更想避免使用它们。我 能够 在sigalrm处理程序中在ucontext-t之间切换,但是posix标准注意到setcontext/swapContext的使用不会在信号处理程序中使用,而且,实际上,在执行此操作时,我注意到Linux和Solaris系统之间的行为不同。

    是这种效应吗? 可能的 实现?如果是,以便携方式?

    3 回复  |  直到 15 年前
        2
  •  1
  •   R.. GitHub STOP HELPING ICE    15 年前

    SIGALRM ucontext_t

        3
  •  0
  •   troutwine    15 年前

    推荐文章