Blocked by QFuture.result () or QFutureWatcher.waitForFinished ();

So I have been using QtConcurrent :: run for some time now and its fantastic. But now I need a function to return an object. So I am using pseudocode

QFutureWatcher<MyObject> fw;
QFuture<MyObject> t1 = QtConcurrent::run(&thOb, &MythreadObjFunc::getList, ConSettings, form, query);
fw.setFuture(t1);
// Both .results() and waitForFinished() block
fw.waitForFinished();
MyObject entries = t1.result();

      

Then I iterate over myObject. The problem is that this is blocking, for example. my main GUI is not responsive. And it is for this reason that I started using QtConcurrent :: run

So what's the recommended way to get my GUI to execute QtConcurrent :: run and return an object, but not block? I was thinking about signals and slots where the signal would be from QtConcurrent :: run, but that would mean it would be from a different thread and I read that it is not recommended.

Thank you for your time.

+3


source to share


2 answers


From QtConcurrent :: run (), you cannot emit any signal. The Runnable function is not a QObject. This is the first thing.

Another thing is that QFutureWatcher :: waitForFinished () blocks execution until the thread finishes executing. This is the intended behavior. If you need to wait for your function to complete, why are you running it in a separate branch? It doesn't make any sense.



The simplest solution is to make your function a member of the class inherited from QObject, move the instance to another thread, start the computation, and emit done (). Qt's signal and slot system is thread safe and this is the ideal way to use it. There is outstanding documentation provided by Qt that covers this topic more than enough. You should start reading here: http://qt-project.org/doc/qt-4.8/threads.html

+1


source


You must not use any function waitForFinished

in the GUI thread. Instead, connect the slot to a future observer signal finished

. See this answer for an example.



+3


source







All Articles