c++ - Qt moveToThread : What resources are brought with the object?

标签 c++ multithreading qt

假设我创建了一个 QObject a 并且它有一个成员 QObject b。 (其实A和B都是QObject的子类,A类有一个成员Bb。)

b 被创建时,它的父级是 0(默认)。在代码中,如果我从未将 b 的父级设置为 a,并且如果我调用 movetothread() 来移动 a 进入一个工作线程,b 是否也会被移入该线程

如果它没有被移动,如果我从工作线程(我将 a 移动到其中的线程)调用 b.init(),它使用 new 运算符创建另一个以 b 作为父对象的 QObject,那么我会得到以下错误,对吗?

QObject: Cannot create children for a parent that is in a different thread

最佳答案

正如 QObject::moveToThread 的 Qt 文档所述:-

Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

在这种情况下,父项是一个对象,其子项是通过在构造函数中传递父项或通过对子项调用 setParent 来设置的。它不是具有指向另一个对象的指针的对象。

In the code, if I never set b's parent to a, and if I call movetothread() to move a into a worker thread, will b be moved into that thread too?

所以,不,如果 b 的父级未设置并且您在 'a' 上调用 moveToThread,'b' 仍将具有原始线程关联。

If it is not moved, if I call b.init() from the worker thread...

如果您将“a”而不是“b”移动到工作线程,那么您不应该直接从工作线程调用 b.init。相反,工作线程 ('a') 中的对象应该发出信号,让原始线程中的对象从连接的槽中调用 b.init

关于c++ - Qt moveToThread : What resources are brought with the object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452850/

相关文章:

c++ - 线程拒绝退出

c++ - C/C++远程消息队列的推荐

c++ - 顶点着色器错误 C5145 : must write to gl_Position using QShaderProgram

Java获取其他类的监视器锁

c++ - 从 QApplication 访问所有线程

c++ - 在 C++ 中的 vector 中存储具有双重继承的对象

multithreading - 如何使Task的updateMessage()立即生效?

c# - 线程通信

c++ - libvlc-qt realloc 执行 libvlc-qt 示例程序时出错

python - 连续 keydown 事件 Pyqt