I have and application with a worker thread. When I try to stop the thread and close my application it crashes.
I am creating the worker and the thread and connecting the signals and slots as:
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();
The ItemMonitor class which is running in the QThread is
#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;
}
and the closeApplication function in my main class is:
void ToDoList::closeApplication(){
while(monitorThread->isRunning()){
std:: cout << "thread not closed" << std::endl;
}
QApplication::quit();
}
what is odd to me is that if I make no attempt to quit the thread and just try to close the applicationt then there are no errors