2013-03-15 170 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(); 

在过程结束()的伎俩。