PDA

View Full Version : Correct way to quit a console application



c1223
22nd November 2014, 10:56
Running a QT5.3 console application on OSX10.8.5. The application has a few threads working. However, when I CMD-Q the application the threads still keep on running. I have to kill the program in Activity Monitor. What is the correct way to exit a program including object deletion and thread quitting?

Cheers

bibhukalyana
22nd November 2014, 13:11
Try this : Before quit the main thread try to quit all running thread and wait for the process to be finished(signal & slot / sleep).
May be it will help you.

anda_skoa
22nd November 2014, 13:23
You need to
1) tell all threads to stop
2) let the main thread wait for the other threads to stop

(1) depends on what the threads do, i.e. if the run an event loop or some processing loop.

(2) can be done by either making the threads signal their exit, count that and quit the main thread when all threads have called in, or by waiting on each thread individually, or by sharing a semaphore between the main thread and the worker threads and have the main thread acquire worker thread count and then worker threads release 1 each.

Cheers,
_

c1223
22nd November 2014, 16:14
Not sure I'm doing this right. Here's some code:


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

LSA listenagain;

QObject::connect(&a, SIGNAL(aboutToQuit()), &listenagain, SLOT(aboutToQuit()));

listenagain.start();

return a.exec();
}

The signal and slot seem to connect fine but then I can't close the other threads.



QThread* thread = new QThread;
showRecord * record = new showRecord(showName, fileName, startHour, startMin, endHour, endMin);
record->moveToThread(thread);
connect(record, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), record, SLOT(process()));
connect(record, SIGNAL(finished()), record, SLOT(deleteLater()));
connect(record, SIGNAL(finished()), thread, SLOT(quit()));
connect(this, SIGNAL(shuttingDown()), record, SLOT(stopRecording()));
thread->start();


void LSA::aboutToQuit() {
emit shuttingDown();
m_timer.stop();
}

Not entirely sure how to delete the showRecord object.

d_stranz
22nd November 2014, 19:51
Not entirely sure how to delete the showRecord object.

If you guarantee that the showRecord instance will not be referenced after it emits the finished() signal, then you should be able to call deleteLater() immediately after you emit the signal, wherever that is. The instance will be deleted next time the event loop runs.

Alternatively, you can add another connect() to the finished() signal when you create the thread.


connect(record, SIGNAL(finished()), record, SLOT(deleteLater()));