无法关闭QThread - 应用程序崩溃

时间:2015-11-10 14:54:19

标签: c++ multithreading qt 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();

在QThread中运行的ItemMonitor类是

#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();
}

对我来说奇怪的是,如果我没有尝试退出线程并且只是尝试关闭应用程序那么就没有错误

1 个答案:

答案 0 :(得分:2)

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

monitor emit finished() - &gt; monitorThread-&gt; quit() - &gt; monitorThread发出finished() - &gt; monitorThread-&GT; deleteLater() 监视器发出finished()信号后,monitorThread将被删除。

void ToDoList::closeApplication(){
    while(monitorThread->isRunning()){//maybe you should check the monitorThread for null
        std:: cout << "thread not closed" << std::endl;
    }
    QApplication::quit();
}