0

I have an Qt app with a window with a grid on it. When User changes current row of the grid I need to do some "work/data base query/calculation" with a piece of information in selected row and display result in status bar. Since this is a small side option (do not want to block main thread) and because of "work/data base query/calculation" may take some time I do it in other thread. The problem pops up then user changes his mind and current row while my side thread is still running. I do not need previous results anymore and I want to stop calculating function running in other thread and free resources taken by it. How should I do that in proper way? I tried different ways of managing threads: -class QThread and examples from https://doc.qt.io/qt-5/qthread.html (does not work for me because while My function is running it blocks thread's event loop and prevent such a good ways of stopping thread as "QThread::quit" and "QThread::exit"); -function QThread::create (does not work either because of created thread does not have event loop at all); -QConcurent::run (according to the Qt documentation - that guy is uncancelable). Yes, there is ultimate way to stop thread - "QThread::terminate", but the documentation highly advice against it as a "dirty" method.

  • You could use an atomic which you check periodically in your compute thread whether to bail out or not. Unfortunately, there are not so much (or better no) ways to cancel a thread from outside (without introducing U.B. or rely on something very system specific). A thread always needs to be a bit co-operative for this - in Qt and in other thread APIs (`std::`, `boost::`) as well. – Scheff's Cat Mar 06 '21 at 10:49
  • FYI: [Qt and std::thread](https://stackoverflow.com/a/61750145/7478597) (Cancel option included - as `Stop` button) – Scheff's Cat Mar 06 '21 at 10:50
  • 1
    No need for an own atomic - simply use QThread::requestInterruption() / isInterruptionRequested() similar to boost::thread (but sadly missing in std::thread) – chehrlic Mar 06 '21 at 10:51
  • @chehrlic Something, I missed til now. (I'm somehow focused on `std::thread` which works beyond Qt as well.) It's probably implemented similar like my "atomic-idea"... – Scheff's Cat Mar 06 '21 at 10:55
  • @cherlic :-) [QThread::interruptionRequested](https://code.woboq.org/qt5/qtbase/src/corelib/thread/qthread_p.h.html#QThreadPrivate::interruptionRequested): `std::atomic interruptionRequested;` – Scheff's Cat Mar 06 '21 at 10:57
  • But it's a build-in and therefore much more convenient. std can do anything but not convenient. – chehrlic Mar 06 '21 at 11:23

0 Answers0