user1026203
user1026203

Reputation:

moveToThread for a member function

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

To put this into context:

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

Is it possible to only move foo() to a new thread? The entire class has a lot of UI calls and other components which may not be thread-safe. I will really appreciate any help or else I will have to reorganize the class and move foo() to a new object.

Upvotes: 3

Views: 304

Answers (1)

Iuliu
Iuliu

Reputation: 4091

You can't move a function to a thread like this. moveToThread changes the affinity of that object to that thread. This means more or less that the signals of that object will be sent to the event loop of the new thread.

I think that you are looking for QtConcurrent for this type of task:

The QtConcurrent::run() function runs a function in a separate thread. The return value of the function is made 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 the Qt Concurrent Framework and QFuture for more details.

Upvotes: 1

Related Questions