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)
    delete xxx;

    1. what should i do when i close the app, eg.teminate this new thread, but how?
    2. 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 using QFuture< T >::waitForFinished() or better off by using a QFutureWatcher 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:

    1. Set QGuiApplication::setQuitOnLastWindowClosed( false ) so that to prevent the application from quitting immediately after the last of its windows is closed.
    2. Connect a slot to the QGuiApplication::lastWindowClosed() signal.
    3. Create a QFutureWatcher< void >* (using new) for every QFuture< void > you create using QtConcurrent::run and keep the instances of the future watchers in the object which receives the last window closed notification.
    4. 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 QFutureWatcher
    5. 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.
    6. On each QFutureWatcher< void >::finished() and on QGuiApplication::lastWindowClosed() check if there are no cached QFutureWatcher's e.g. no futures are running.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.