MoveToThread for member function

Is it possible to move a member function to a new thread instead of the whole class?

To do it in context:

    class FooBar : public QObject {
    Q_OBJECT
    // some other function that deals with the UI changes    
    private:
        get foo();
    }; 

      

Can I only move foo()

to a new thread? The whole class has many calls to the UI and other components that may not be thread safe. I would really appreciate any help, otherwise I will have to refactor the class and move foo()

to a new object.

+3


source to share


1 answer


You cannot move a function into a thread like this. moveToThread

changes the affinity of this object for this stream. This means more or less that signals from this object will be sent to the event loop of the new thread.

I think you are looking QtConcurrent

for this type of problem:

The QtConcurrent :: run () function runs the function on a separate thread. The return value of the function is available through the QFuture API.



 extern void aFunctionWithArguments(int arg1, double arg2, const QString &string);

 int integer = ...;
 double floatingPoint = ...;
 QString string = ...;

 QFuture<void> future = QtConcurrent::run(aFunctionWithArguments, integer, floatingPoint, string);

      

See Qt Concurrent Framework and QFuture for more details.

+1


source







All Articles