1

Qthreadを使用しようとしていますが、スレッドが実際にいつ実行されるかがわかりません。スレッドを作成している関数が終了したときにのみ実行を確認できましたが、現在の関数を1回の実行後に終了させたくありません。この関数内でループ内でスレッドを何度も実行したいと思います。

////////////////////////////////////////////////// ////////////////////

// --- PROCESS ---
// Start processing data.
void GrayDisplay::process() 
{
    std::cout << "Thread context!" << std::endl;  //I never see this print

    emit finished();
}


void gig::OnPlay()
{
    //Create thread and assign selected
    QThread* thread = new QThread;

    if(ui->colorBox->currentIndex() == 0 )
    {
        GrayDisplay* display = new GrayDisplay();
        display->moveToThread(thread);
        connect(display, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
        connect(thread, SIGNAL(started()), display, SLOT(process()));
        connect(display, SIGNAL(finished()), thread, SLOT(quit()));
        connect(display, SIGNAL(finished()), display, SLOT(deleteLater()));
        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

        std::cout << "Creating Thread!" << std::endl;
    }
    else
    {
        cout << "\nInvalid mode selected";
        return;
    }

    pSemaphore->acquire();
    run = true;
    pSemaphore->release();

    //Read data
    while(run)  //set false by click event
    {
        QCoreApplication::processEvents();
        Sleep(33);
        if (thread->isRunning())  //Always prints and I expect just the first loop iteration to print, not infinitely as it does
            cout << "Worker is-STILL-Running\n";

        thread->start();
        QApplication::exec();
        QCoreApplication::processEvents();
//      while (!thread->isFinished())
//      {
//          QApplication::exec();
//          QCoreApplication::processEvents();
//      }   //Never returns
    }   //WHILE RUN LOOP

    return;
}

ここで同様のスレッドを見てきましたが、解決策は常に次のようになります。QCoreApplication :: processEvents(); これは私を助けていないようです。スレッドを作成して開始すると、スレッドは常に実行されているように見えますが、何も実行せず(printステートメントは表示されません)、終了しません。スリープを追加して、新しいスレッドを開始する必要が生じる前に各ループが終了するまでにかかる時間をシミュレートしました。その時までに前のスレッドが終わっていると思います。単純なバージョンを正しく機能させようとしていますが、何が欠けているのか理解できません。OnPlay()関数を終了するときにのみスレッドを削除したいのですが、終了するまでスレッドを何度も実行します。

4

1 に答える 1

0

次のスレッドで私と同じ問題を抱えていると思います:なぜ私のスレッドは正常に終了しませんか? .

問題は、スレッドのイベント ループがprocess() が戻った後にのみ確立されることです。これは、この時間より前にスレッドに送信されたすべての終了イベントが削除されることを意味します。

qeventloop.cpp:

// remove posted quit events when entering a new event loop
QCoreApplication *app = QCoreApplication::instance();
if (app && app->thread() == thread())
    QCoreApplication::removePostedEvents(app, QEvent::Quit);

私の場合、単純な

QThread::currentThread()->quit();

process() の最後にトリックを行いました。

于 2013-03-26T13:27:32.880 に答える