0

私のコードは次のとおりです。

while (DAQ is ON) {
do stuff on vars;
if(f(vars) > thr)
update vars;
}

if 条件はたまにしかトリガーされず、while ループの前のセクションで使用されたすべての変数を更新します。ループ全体は通常 (必要に応じて) リアルタイムで実行されますが、if 条件も実行する必要がある場合は遅れます。別のスレッドで if 条件を実行するにはどうすればよいですか? 必要なだけ時間がかかる可能性があります。更新が遅れて発生しても問題ありません。while ループの残りの部分をリアルタイムで実行し、「if」スレッドが完了するたびに変数が更新されるようにしたいだけです。

コンテキスト: C++/JUCE フレームワーク、リアルタイム信号処理。

4

1 に答える 1

2

ここで作業するコアが少なくとも 2 つあると仮定します。そうでなければ、マルチスレッドは役に立ちません。ここでは C++11 マルチスレッド セマンティクスを使用しているため、コンパイラで C++11 言語仕様を有効にする必要があります。

#include <condition_variable>
#include <thread>
#include <mutex>

using namespace std;

condition_variable cv;
mutex mtx;
bool ready = false;

void update_vars() {
    while( true ) {
        // Get a unique lock on the mutex
        unique_lock<mutex> lck(mtx);
        // Wait on the condition variable
        while( !ready ) cv.await( mtx );
        // When we get here, the condition variable has been triggered and we hold the mutex
        // Do non-threadsafe stuff
        ready = false;
        // Do threadsafe stuff
    }
}

void do_stuff() {
    while( true ) {
        // Do stuff on vars
        if ( f(vars) ) {
            // Lock the mutex associated with the condition variable
            unique_lock<mutex> lck(mtx); 
            // Let the other thread know we're ready for it
            ready = true;
            // and signal the condition variable
            cv.signal_all();
        }
        while( ready ) {
            // Active wait while update_vars does non-threadsafe stuff
        }
    }      
}


int main() {
    thread t( update_vars );
    do_stuff()
}

上記のコード スニペットが行うことは、update vars を実行するセカンダリ スレッドを作成することです。これはハングアップし、メイン スレッド (do_stuff を実行している) が条件変数を介してシグナルを送信するまで待機します。

PS、おそらく先物でもこれを行うことができますが、それらに基づいて答えるのに十分な作業をしていません。

于 2014-09-12T02:42:45.117 に答える