运行错误: QObject: 无法创建子线程, 因为父线程位于不同的线程? 到底是什么鬼?
运行错误: QObject: 无法创建子线程, 因为父线程位于不同的线程? 到底是什么鬼?
(Parent is QThread(0x7ffe4a5a1280), parent's thread is QThread(0x557f9e497e50), current thread is QThread(0x7ffe4a5a1280)
父亲是QThread 0x7ffe4a5a1280, 父亲线程是QThread(0x557f9e497e50), 当前线程是QThread(0x7ffe4a5a1280) ?
字面翻译过来说得确实不太清楚, 还是要翻译成人话.
先看一个简单的例子.
$ cat main.cpp#include
#include
#include "threadtest.h"int main(int argc, char *argv[])
{QGuiApplication app(argc, argv);ThreadTest tt;tt.start();return app.exec();
}
hjj@hjj:~/test/test_thread$ cat threadtest.h
#ifndef THREADTEST_H
#define THREADTEST_H
#include
#include class Class1 : public QObject
{
public:Class1(QObject* parent) : QObject(parent){}
};class ThreadTest : public QThread
{
public:ThreadTest(){qDebug() << "ThreadTest::ThreadTest, construct thread = " << QThread::currentThread();}void run() override{qDebug() << "run thread = " << QThread::currentThread();qDebug() << "construct thread " << this->thread();m_class = new Class1(this);}private:Class1* m_class = nullptr;
};#endif
运行:
./test_thread
ThreadTest::ThreadTest, construct thread = QThread(0x56399a8aee50)
run thread = QThread(0x7ffc9379d0f0)
construct thread QThread(0x56399a8aee50)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QThread(0x7ffc9379d0f0), parent's thread is QThread(0x56399a8aee50), current thread is QThread(0x7ffc9379d0f0)
问题出在 new Class1(this) 上 翻译成人话:
1. 你当前的线程是run 线程, 其线程ID 为 QThread(0x7ffc9379d0f0)
2. 你传递给Class1的参数是(this), this 属于ThreadTest 的构造线程的变量. ThreadTest 属于另一个线程,其ID 为QThread(0x56399a8aee50)
说白了,在一个线程中,构建一个对象时,不能传递其它线程的变量地址(常见是其构造线程对象地址)到QObject.
为啥会有这种限制, 估计是QObject 的限制. 估计它在处理一些消息分发时要简化架构,这个线程处理另一个线程的对象会出问题.
总结一下它出现的条件.
1. 你想给QObject 传递指针,
2. 传递的指针与指针所在的线程不是同一个线程.
如何消除这种错误: 其中方法1,2需要调整你的程序架构(优化). 3可能是简单办法.
1. 修改Class1, 不继承QObject. 但这可能不是你想要的.
2. 去掉this, 传NULL 指针. 相当于还是去掉了QObject, 可能不是你想要的.
3. 将 m_class = new Class1(this); 提到构造函数中. 传递的this变量是构造线程变量到QObject.
这可能是最好的办法. 经测试可行. 此时threadtest.h 如下图示.
#ifndef THREADTEST_H
#define THREADTEST_H
#include
#include class Class1 : public QObject
{
public:Class1(QObject* parent) : QObject(parent){}
};class ThreadTest : public QThread
{
public:ThreadTest(){qDebug() << "ThreadTest::ThreadTest, construct thread = " << QThread::currentThread();m_class = new Class1(this);}void run() override{qDebug() << "run thread = " << QThread::currentThread();qDebug() << "construct thread " << this->thread();}private:Class1* m_class = nullptr;
};#endif
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
