2013-03-15 124 views
1

我試圖用一個QThread的,但似乎無法弄清楚當線程實際執行。我只能在創建線程的函數退出時才能看到它正在執行,但我不想在執行一次後退出當前函數。我想在該函數的循環中多次運行該線程。QT線程永遠不會運行

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

// --- 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(); 這似乎並沒有幫助我。如果我創建並啓動線程,它似乎總是在運行,但從不執行任何操作(從來沒有看到我的打印語句)並且永遠不會結束。我添加了睡眠模擬每個循環在每次循環完成之前需要開始一個新線程的時間。我預計到那個時候前面的線程已經完成了。我試圖讓一個簡單的版本正常工作,但無法弄清楚我錯過了什麼。我只想在離開OnPlay()函數時刪除線程,但多次執行線程直到我決定退出。

+0

爲什麼你'的QApplication :: EXEC();'在那裏? – Mat 2013-03-15 05:30:37

+1

因爲QApplication :: exec();永遠不會完成。 – 2013-03-15 06:42:39

+0

只是一些有人建議在許多論壇上我搜索,所以我想我會嘗試之一。看起來可能是這個問題。過了一段時間我纔開始嘗試任何東西,這似乎是一個問題。謝謝。 – user2172035 2013-03-15 17:40:28

回答

0

我覺得你有同樣的問題,我在下面的線程:Why do my threads not exit gracefully?

問題是你的線程的事件循環只有在 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(); 

在過程結束()的伎倆。