0

問題: まず、これは私の問題の単純化された例であり、実際には他の誰かによって既にプログラムされている大規模なフレームワークの一部であり、そこに自分のコードを適応させる必要があります。

私には3つの機能があります。関数のうちの 2 つ (function1 と function2) は、プログラムの他の部分によって非同期と同期の両方で呼び出されています。最後の関数 (function3) は、while ループのように継続的に実行されます。これが行う唯一のことは、コードの反復ごとにイベント コードを起動することです。他の2つの関数の1つが反復を完了した/呼び出されたときはいつでも、この最後の関数を実行したいだけです。それらが呼び出される方法/時期を変更することはできません。コードの実行をブロックしてブロックを解除することしかできません。

私はC ++にかなり慣れていないので、ミューテックスを使用してこれを解決しようとしましたが、うまくいきませんでした. コードを追加できますが、実際には説明したとおりです。

void function1(){  // this function is called by other parts of the program
//some code
}

void funtion2(){  //this function is also called by other parts of the program
//some other code
}

void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it

fireEvent();//fires an event to run some other code
}

したがって、function3 はブロックされない限り常に実行されます。他の関数の 1 つが 1 回実行されるたびに関数を実行したいと思います。前に言ったように、自分で function3 を呼び出すことはできません。関数内のコードを操作することしかできません。

これについて最善の方法は何ですか?

激しいグーグル検索の後、条件変数、セマフォ、およびミューテックスしか思いつきませんでしたが、それらを正しく実装する方法を知るには十分ではありません。

ヘルプ/入力/ヒントは大歓迎です。

4

1 に答える 1

1

簡単な方法は次のようになります。

mutex g_mutex;
condition_variable g_cond;
bool flag = false;
void function1(){ // this function is called by other parts of the program
    //some code
    lock_guard<mutex> lock(g_mutex);
    flag = true;
    g_cond.notify_one();
}

void funtion2(){ //this function is also called by other parts of the program
    //some other code
    lock_guard<mutex> lock(g_mutex);
    flag = true;
    g_cond.notify_one();
}

void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it
    {
        unique_lock<mutex> lock(g_mutex);
        g_cond.wait(lock, []{return flag;}); // wait here until func1 or func2 have been called
        flag = false;
    }
    fireEvent();//fires an event to run some other code
}

int main() {
// your code goes here
return 0;
}

しかし、これはfunction3他の2つのうちの1つが呼び出されるまであなたをブロックします。したがって、これは動作の変更であり、ロック競合が追加されます。

于 2013-09-23T14:43:18.860 に答える