2

Similar to this question, I'd like to limit the execution time of a function--preferably with microsecond accuracy--in C. I imagine that C++ exceptions could be used to achieve a result similar to this Python solution. Though it's not ideal, such an approach is wholly unavailable in plain C.

I wonder, then, how might I interrupt the execution of a function after a certain time interval in C on a Posix system? For relatively simple situations a bit of silly business works just fine, but that adds a fair amount of code orthogonal to the problem solution. Let's say I have a function like so:

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

I want to run run boil on an egg*, interrupting it every 50μs to check do something like so:

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

I realize that pthreads could be used to do this, but I'm rather more interested in avoiding their use. I could switch between ucontext_t's in a SIGALRM handler, but the POSIX standard notes that the use of setcontext/swapcontext is not to be used in a signal handler and, indeed, I note differing behaviors between Linux and Solaris systems when doing so.

Is this effect possible to achieve? If so, in a portable manner?

4

3 に答える 3

1

You can either use threads, or have the function poll a timer (or a global variable set by SIGALRM handler), then save its state and exit when the allotted time has expired. Use of ucontext_t is deprecated and should never be used in new code, at all, much less from signal handlers.

于 2010-09-14T03:42:27.730 に答える
0

私が望む解決策は突然私に起こります: goto! 制限したい関数の直後にジャンプポイントを設定し、タイマーを設定し、SIG*ALRM を処理するシグナルハンドラーで関数の後の命令にジャンプするだけです。

于 2010-09-14T13:35:45.513 に答える
0

ここで探している一般的な機能は、コスト施行と呼ばれることに注意してください。たとえば、WellingsまたはLeung らのこの記事を参照してください。al. の素晴らしい本。上記の回答は、ユーザー空間でそれを達成することに焦点を当てています。一部の RTOS または言語は、一般的なメカニズムとして (Linux ではなく) サポートしています。

これを提供する OS の例として、AUTOSAR OS (リンクされた仕様)があります。この OS は実行時間の強制を提供することに注意してください。これは、期限の強制とは少し異なります。 実行時間の強制は、実際に費やされたコストを測定する機能に依存しているため (通常はハードウェアの連携により)、ますます難しくなっています。今日のプロセッサの複雑さにより、これを測定することは困難で費用がかかります — 言うまでもなく、測定値の意味は (非線形実行やその他のあらゆる種類の優れた機能のために) 解釈するのが難しく、したがって (コードの特定のセクションの実行時間の最悪または一般的なケースの見積もり。

少し本題から外れますが、ここでは Ada が言語レベルでより厳密な一連の機能を提供しているため、役に立ちませんが、これらの Ada 要件が Linux でどのように実装されているかを理解することはできます。Ada 言語仕様は、理論的根拠のドキュメントを提供するという点で独特です。出発点として、リアルタイムのプリエンプティブ アボートに関するセクションを参照してください。

于 2010-10-02T13:18:07.597 に答える