2017-12-28 13 views

答えて

0

Please avoid using nested loops when possible.しかしはあなたがの周りに方法がないことが確実であれば、あなたはしていない解雇し、それらのどのている信号のどの格納するための方法を持っている、と(イベント・ループを終了する必要がありますつまり、イベントループのQEventLoop::quitに接続された信号を出力することによって)、すべての信号が起動されたときに限ります。ここで

が異なる間隔で10のQTimer Sを使用し、それらのすべてを待って、ネストされたイベントループを終了する前に発射する最小の例である:

#include <QtCore> 
#include <algorithm> 

int main(int argc, char* argv[]) { 
    QCoreApplication a(argc, argv); 
    const int n = 10; 
    //10 timers to emit timeout signals on different intervals 
    QTimer timers[n]; 
    //an array that stores whether each timer has fired or not 
    bool timerFired[n]= {}; 
    QEventLoop loop; 
    //setup and connect timer signals 
    for(int i=0; i<n; i++) { 
     timers[i].setSingleShot(true); 
     QObject::connect(&timers[i], &QTimer::timeout, [i, &timerFired, &loop]{ 
      qDebug() << "timer " << i << " fired"; 
      timerFired[i]=true; 
      //if all timers have fired 
      if(std::all_of(std::begin(timerFired), std::end(timerFired), 
          [](bool b){ return b; })) 
       loop.quit(); //quit event loop 
     }); 
     timers[i].start(i*i*100); 
    } 
    qDebug() << "executing loop"; 
    loop.exec(); 
    qDebug() << "loop finished"; 

    QTimer::singleShot(0, &a, &QCoreApplication::quit); 
    return a.exec(); 
} 
+0

う10個のスレッドを作成ネスティングとまったく同じものになりますループ?私は10個の非同期タスクを作成するために1つのイベントを使用したいと思っていました。私はあなたが提供したリンクを簡単に読んで、これはノー・ノーかもしれないと思われます。 –

+0

これらは確かに同じものではありません。*ネスト・イベント・ループ*という用語は、イベント・ループが別のイベント・ループを開始していることを指します(多分何らかのイベントへの応答として)。スレッドを使用することはまったく別の動物であり、スレッドは並列実行パスを提供します。たとえば、2つの異なるものを並行して実行するために使用できます。 Qtでは、Threadsはイベントループを実行して、[* live in them *](https://doc.qt.io/qt-5/qobject.html#thread-affinity)のQObjectのイベントを配信することができます。 。 – Mike

+0

10個の非同期タスクを開始したいだけなら、['QtConcurrent :: run'](https://doc.qt.io/qt-5/qtconcurrentrun.html)を使うことができます。スレッドを自分で管理します。結果を[QFuture :: waitForFinished'](https://doc.qt.io/qt-5/qfuture.html#waitForFinished)または['QFutureWatcher'](https)を使用して非同期的に待つことができます://doc.qt.io/qt-5/qfuturewatcher.html)に接続し、['finished()']](https://doc.qt.io/qt-5/qfuturewatcher.html#finished)シグナルに接続します。 – Mike

関連する問題