多线程中,每个线程都有自己的栈空间,在主线程(UI线程)中创建的对象,处于主线程的栈空间,在windows中出现提示QObject: Cannot create children for a parent that is in a different thread,在中标麒麟的系统中会出现段错误,崩溃。
错误例子:
class TestObject{
public:
TestObject(){}
private:
QUdpSocket m_sock;
}
void fun()
{
TestObject* obj = new TestObject;
QThread thread;
obj->moveToThread(&thread);
thread.start();
}
正确做法1:
class TestObject{
public:
TestObject():m_sock(this) {} //成员变量挨个指定this为父对象
private:
QUdpSocket m_sock;
}
void fun()
{
TestObject* obj = new TestObject;
QThread thread;
obj->moveToThread(&thread);
thread.start();
}
正确做法2:
class TestObject{
public:
TestObject(){}
void moveToThread(QThread *thread) //重写moveToThread,成员变量挨个move到新线程的栈空间
{
m_sock.moveToThread(thread);
Object::moveToThread(thread);
}
private:
QUdpSocket m_sock;
}
void fun()
{
TestObject* obj = new TestObject;
QThread thread;
obj->moveToThread(&thread);
thread.start();
}
正确做法3:
class TestObject{
public:
TestObject();
public slots:
void initSlot(); //利用信号槽,在槽中创建对象
private:
QUdpSocket* m_sock;
}
TestObject::TestObject()
{
connect(this, &TestObject1::initSignal, this, &TestObject1::initSlot, Qt::QueuedConnection);
emit initSignal();
}
void TestObject::initSlot()
{
m_sock = new QUdpSocket;
}
void fun()
{
TestObject* obj = new TestObject;
QThread thread;
obj->moveToThread(&thread);
thread.start();
}