multithreading - 在 QObject 构造函数中使用运算符 'new'(多线程)

标签 multithreading qt

This article详细说明 QThread 的“正确”使用说

By the way, one extremely important thing to note here is that you should NEVER allocate heap objects (using new) in the constructor of the QObject class as this allocation is then performed on the main thread and not on the new QThread instance, meaning that the newly created object is then owned by the main thread and not the QThread instance. This will make your code fail to work. Instead, allocate such resources in the main function slot such as process() in this case as when that is called the object will be on the new thread instance and thus it will own the resource.



我理解的第一部分是堆对象的分配(从而运行构造函数)发生在创建 QObject 的线程中。之后才使用 QThread::moveToThread 将其推送到 QThread。

但是我不太明白提到的所有权问题,特别是

meaning that the newly created object is then owned by the main thread



它当然不是指资源的标准所有权,因为在 Qt 中可以通过父子机制轻松控制。

这是否意味着多线程的底层内存管理机制(或 QThread 尽管据我所知这只是操作系统线程实现的包装器)?因为每个存储其资源的线程都有一个不同的“内存段/缓存”?

如果是这种情况,我可以看到问题,但找不到完整的答案或解释。谢谢!

最佳答案

它指的是 QObject 存在于某些线程中的事实——默认情况下,创建它们的线程。 “Live”指的是 QObject 不是可重入的,也不是线程安全的:一个 QObject 只能从它所在的线程中使用。

不过,这个建议是错误的。这样做是完全安全的

class Foo : public QObject {
    Q_OBJECT
    Foo() {
        m_suboject = new Bar(this);
        m_other = new Fie("/dev/blah", this);
        ...

关键在于this参数,意味着子对象正确地以 Foo 实例为父对象。因此,当你做
Foo *foo = new Foo;
foo->moveToThread(thread);

以“foo”为根的整个对象树将被移动到新线程中(moveToThread 移动一个对象及其所有子对象)。

关于multithreading - 在 QObject 构造函数中使用运算符 'new'(多线程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811061/

相关文章:

c# - Application Insight 的 TelemetryClient 线程安全吗?

c++ - Qt 线程出错

c++ - 无法使用 OpenCV 打开两个摄像头 - 多线程摄像头读取

C - 使用并发线程查找三个数字以添加到目标值

regex - 在 QT 中验证由点 (.) 分隔的字符串

qt - 用 Qt 图像替换一些文本

C++ - 生产者/消费者只允许消费定义的 block

qt - 在 Qt Creator 4.8 中禁用 MSVC 链接器警告

c++ - Qt声子媒体对象错误

c++ - 静态 QMap 的冲突声明