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;
}