Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
how to release the memory in QtConcurrent the new thread func?
opengpu2 last edited by
before the main()
void func(pointer* p)
Class* xxx = new Class();
- what should i do when i close the app, eg.teminate this new thread, but how?
- can delete xxx; implement? will the memory leak in this way? if it does leak, what should i modify the code above?
napajejenunedk0 last edited by
You will always leak in your case, I presume. First off I would suggest you to use QScopedPointer, not
delete. Second, when quitting your application you should wait for all futures to finish and then quit. The line:
QFuture< void >object. One way is to wait the future to finish either using
QFuture< T >::waitForFinished()or better off by using a
QFutureWatcherwhich would asynchronously notify you when the future is ready. You could also cancel the future upon a request to quit the application.
So the steps are:
- Set QGuiApplication::setQuitOnLastWindowClosed( false ) so that to prevent the application from quitting immediately after the last of its windows is closed.
- Connect a slot to the QGuiApplication::lastWindowClosed() signal.
- Create a
QFutureWatcher< void >*(using new) for every QFuture< void > you create using
QtConcurrent::runand keep the instances of the future watchers in the object which receives the last window closed notification.
- Hook to the
finished()signal of the
QFutureWatcher< void >in the object which also tracks whether application quit has been requested. Remove the kept instance of the
- Upon receiving the last window closed notification set a flag in the same object that an application quit has been requested - the last window has been closed.
- On each
QFutureWatcher< void >::finished()and on
QGuiApplication::lastWindowClosed()check if there are no cached
QFutureWatcher's e.g. no futures are running.