成员函数的moveToThread

moveToThread for a member function

本文关键字:moveToThread 函数 成员      更新时间:2023-10-16

是否可以将成员函数移动到新的线程而不是整个类?

将此放在上下文中:

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

是否可以只将foo()移动到新线程?整个类有很多UI调用和其他组件,这些组件可能不是线程安全的。我将非常感谢任何帮助,否则我将不得不重新组织类并将foo()移动到一个新对象。

不能像这样将函数移动到线程中。moveToThread改变该对象与该线程的相关性。这或多或少意味着该对象的信号将被发送到新线程的事件循环。

我认为您正在为这种类型的任务寻找QtConcurrent

QtConcurrent::run()函数在一个单独的线程中运行一个函数。函数的返回值可通过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);

有关更多详细信息,请参阅Qt并发框架和QFuture。