2015-11-10 2 views
1

У меня есть приложение с рабочим потоком. Когда я пытаюсь остановить поток и закрыть приложение, он сработает.cant close QThread - сбой приложений

Я создаю рабочий и нить и присоединительные сигналы и слоты, как:

QPointer<QThread> monitorThread(new QThread()); 
QPointer<ItemMonitor> monitor(new ItemMonitor(items)); 
monitor->moveToThread(monitorThread); 

//closeInitiated signal emitted when custom close button is clicked 
connect(this, SIGNAL(closeInitiated()), monitor, SLOT(finishUp())); 
connect(monitor, SIGNAL(finished()), monitorThread, SLOT(quit())); 
connect(monitor, SIGNAL(finished()), monitor, SLOT(deleteLater())); 
connect(monitor, SIGNAL(finished()), this, SLOT(closeApplication())); 
connect(monitorThread, SIGNAL(started()), monitor, SLOT(beginMonitoring())); 
connect(monitorThread, SIGNAL(finished()), monitorThread, SLOT(deleteLater())); 

//start monitoring 
monitorThread->start(); 

Класс ItemMonitor, который работает в QThread является

#include "itemmonitor.h" 
#include "todoitem.h" 
#include <QObject> 
#include <iostream> 
#include <QTimer> 


ItemMonitor::ItemMonitor(std::vector< QPointer<ToDoItem> >& items_) 
:items(items_), 
shouldRun(true){ 
    std::cout << "Monitor created" << std::endl; 
} 


void ItemMonitor::beginMonitoring(){ 
    if(shouldRun){ 
     for(int i=0; i<items.size(); i++){ 
      items[i]->setSecsTillDeadline(); 
     } 
     QTimer::singleShot(100, this, SLOT(beginMonitoring())); 
    }else{ 
     emit finished(); 
    } 
} 

void ItemMonitor::finishUp(){ 
    shouldRun = false; 
} 

и функция closeApplication в моем основной класс:

void ToDoList::closeApplication(){ 
    while(monitorThread->isRunning()){ 
     std:: cout << "thread not closed" << std::endl; 
    } 
    QApplication::quit(); 
} 

Что странно для меня, так это то, что если я не сделаю попытку бросить нить и просто попытаться закрыть applicationt то нет никаких ошибок

+0

Возможно, ваш звонок здесь «connect (monitor, SIGNAL (finished()), это, SLOT (closeApplication())); может вызвать проблему, если вы удаляете при очистке приложения. Вы пытаетесь закрыть приложение дважды? Я не вижу, где вы пытаетесь остановить поток в своей закрытой функции. –

+0

«Сбои» не имеет смысла. По крайней мере, вы должны посмотреть на трассировку стека. – SergeyA

+0

Когда я пытаюсь отлаживать приложение в отладчике qt, он никогда не запускается и не замораживает весь мой компьютер ... Мне нужно перезагрузить, поэтому я не вижу трассировку стека – user2145312

ответ

2
connect(monitor, SIGNAL(finished()), monitorThread, SLOT(quit())); 
connect(monitorThread, SIGNAL(finished()), monitorThread, SLOT(deleteLater())); 

монитора испускает завершены() -> monitorThread-> бросить курить() -> monitorThread испускает закончил() -> monitorThread-> deleteLater () после того, как монитор излучает законченный() сигнал, мониторThread будет удален.

Смежные вопросы