how to release the memory in QtConcurrent the new thread func?
-
QtConcurrent::run(func, p);
before the main()
@
void func(pointer* p)
{
Class* xxx = new Class();
while (true)
{
xxx->tick();
}
delete xxx;
return;
}
@- 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?
thank you
-
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:QtConcurrent::run(func, p);
... generates
QFuture< void >
object. One way is to wait the future to finish either usingQFuture< T >::waitForFinished()
or better off by using aQFutureWatcher
which 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 usingQtConcurrent::run
and keep the instances of the future watchers in the object which receives the last window closed notification. - Hook to the
finished()
signal of theQFutureWatcher< void >
in the object which also tracks whether application quit has been requested. Remove the kept instance of theQFutureWatcher
- 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 onQGuiApplication::lastWindowClosed()
check if there are no cachedQFutureWatcher
's e.g. no futures are running.