2

cで並行性を可能にする利用可能な関数とライブラリがあることを私は知っています。

(pthread.h、fork()など)

しかし、実際に複数のスレッドを使用せずに、Cで並行性をシミュレートする方法があるかどうか疑問に思いました。

シナリオ例:

計算を実行および出力するメインプログラムループがあります。どういうわけか、別の関数がメイン関数に時刻が午後12時であることを通知し、ユーザーが昼食に出かけるときにプログラムは計算の出力を停止する必要があります。12:30に、この関数はメイン関数に計算の出力を再開するように通知します。

誰かがこれを行う方法について正しい方向に私を向けることができますか?

編集:

本質的に、これを行うには2つの方法があるはずだと私は信じています。

1つ目は、メインプログラムが常に代替機能をチェックするため、時計が12:00になったことを認識します。(これは非常に簡単で、私はこれを行う方法を知っています)

2つ目は、必要に応じて(つまり、12:00と12:30に)代替機能がメインプログラムに接続するようにすることです。

4

2 に答える 2

2

そのために使用できる単純なタイマーが必要なように思えますalarm()

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

volatile unsigned stop_working = 0;

void alarm_handler(int signum)
{
    stop_working = 1;
    //alarm(1); //reschedule alarm
}

int main()
{        
    signal(SIGALRM, alarm_handler);
    alarm(1); //schedule alarm in seconds

    while (!stop_working) {
      //do some work
    }
}

ただし、コルーチンのようなものが必要な場合は、次のような関数を使用してユーザーレベルのスレッド(またはファイバーmakecontext())を調べる必要があります。swapcontext()

CreateWaitableTimer()注:この例はUNIX / Linux固有であり、MinGWの場合は、、などの関数を使用してwinapiを使用する必要がありますSetWaitableTimer()。詳細については、MSDNを参照してください。

于 2012-11-17T21:12:01.930 に答える
0

A concurrency model (simulated or not) would make sense if you had multiple tasks that you need to run at the same time. In this case it appears you only have one task to run.

If the only requirement that you have is that your calculations stop at 12:00 and restart at 12:30 then all you need is to make sure your calculations can be divided into small steps, so that you have a chance to check the conditions for starting and stopping in between steps. Here is some pseudo-code:

while (true) {
    current_time = get_current_time();
    if (current_time >= 12:00 and current_time < 12:30)
        sleep(12:30 - current_time);
    else
        perform_calculation_step();
}

If the starting and stopping conditions are more complex than what you indicated in your example you could abstract the start/stop logic into a separate function. Example:

while (true) {
    wait_if_necessary(); // this blocks when the app is not allowed to run
    perform_calculation_step()
}

I hope this helps!

于 2012-11-17T21:52:02.350 に答える