PDA

View Full Version : want to get thread to stop when application exits



dan146
20th April 2012, 18:36
I need to get a worker thread to clean up and exit when the application exits. The thread normally would continue to function forever(sending serial messages) but when someone clicks the X in the upper right of the application window, I need the thread to finish. Currently, I have to use the windows task manager to kill the thread, which is not acceptable long term.

I'm using the following line to spawn the thread:
QFuture<void> future = QtConcurrent::run(monitor_thread);

I thought all I need to do is set a flag, then the thread will see the flag and clean up, but I'm having trouble understanding where to set the flag. I put it in the MainWindow destructor(see below), but for some reason it's not working. Maybe I should handle the signal for the exit event, but I'm not sure how. Any suggestions would be appreciated.

MainWindow::~MainWindow()
{
app_trying_to_exit = true;
delete ui;
}

ChrisW67
21st April 2012, 06:26
How and how often is your thread function looking at the app_trying_to_exit flag?

viulskiez
21st April 2012, 08:12
Maybe QCoreApplication::aboutToQuit() signal may help.

wysota
21st April 2012, 08:59
Maybe QCoreApplication::aboutToQuit() signal may help.

It won't help because the thread doesn't have an event loop.

For long running threads such as this I would advise against using threads from the thread pool (which is what QtConcurrent::run() does) because on single cpu systems this might starve the application.

dan146
24th April 2012, 22:22
In response to Chrisw67, the thread checks this flag right after the gui thread releases a lock, so the destructor actually looks like this:

MainWindow::~MainWindow()
{

fprintf(dfp,"\n\n=================EXITING APPLICATION====================\n\n");
app_trying_to_exit = true;
sysmutex.unlock();
delete ui;
}

Note I don't see the output from fprintf in my log file.


In response to Wysota, I will look into non thread pool threads. Note the thread waits on a lock for 99% of the time, so maybe starving the app this isn't a problem.

wysota
24th April 2012, 22:31
It is, because the thread is created and reserved. The fact that it sleeps is meaningless. If you try to start another thread from the pool that has only one thread, the thread will not start until the first one exits (which happens when the application is destroyed) so in practice the second thread will not run at all. You would have to release the thread before going to sleep on the mutex and reserve it back again when you are woken up. However it simply makes no sense to complicate things that much in this particular case since it's much easier to use QThread.

dan146
3rd May 2012, 00:07
Sorry for the slow reply, I'm juggling 3 projects. Yes I used QThread and it works great now! The flag is now seen by the thread and it exits properly.
Thanks!