1

我正在尝试使用 Qthread,但似乎无法弄清楚线程何时实际执行。我只能在创建线程的函数退出时看到它的执行,但我不希望我当前的函数在单次执行后退出。我想在这个函数的循环中多次运行线程。

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

// --- 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 回答