Qt多线程解决思路
Qt多线程
这是部分代码,为什么socket->write(data);会导致QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNativeSocketEngine(0x3432a0), parent's thread is MyThread(0x343310), current thread is QThread(0x341550)。我试了下,注释socket->write(data);不会出错。
------解决方案--------------------
创建一个 worker 类, 然后 moveToThread, 或者直接使用野蛮方法 在构造函数中 调用 moveToThread(this);
------解决方案--------------------
应该把socket描述符通过自定义事件的方式传递给新线程,在新线程中创建 QTcpSocket ,然后调用 setSocketDescriptor 把收到的 socket描述符设置给 QTcpSocket 对象。
这是比较好的做法。
void MyThread::run()
{
qDebug()<<"thread starts here.";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readyread()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
qDebug()<<"Client connected";
exec();
}
void MyThread::readyread()
{
QByteArray data = socket->readAll();
qDebug()<<this->socketDescriptor<<"data in";
socket->write(data);
qDebug()<<data;
}
这是部分代码,为什么socket->write(data);会导致QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNativeSocketEngine(0x3432a0), parent's thread is MyThread(0x343310), current thread is QThread(0x341550)。我试了下,注释socket->write(data);不会出错。
------解决方案--------------------
创建一个 worker 类, 然后 moveToThread, 或者直接使用野蛮方法 在构造函数中 调用 moveToThread(this);
------解决方案--------------------
应该把socket描述符通过自定义事件的方式传递给新线程,在新线程中创建 QTcpSocket ,然后调用 setSocketDescriptor 把收到的 socket描述符设置给 QTcpSocket 对象。
这是比较好的做法。