如何在Qt中的线程之间共享QObjects

How to share QObjects between threads in Qt

本文关键字:线程 之间 共享 QObjects Qt      更新时间:2023-10-16

我对QT很陌生,但在其他一些平台中使用了多线程方法。我正在一个我在main中创建的QThread中进行轮询。为了做到这一点,我将其子类化。我需要将一些参数(QObjects)传递给线程,让它做一些工作。但当我尝试使用它们时,我的程序会崩溃。所以我的问题是如何在两个线程中使用相同的QObjects?我将使用互斥体进行同步,但我无法摆脱这个错误"无法为不同线程中的父线程创建子线程"

有四个静态函数对QSerialPort对象起作用。

QSerialPort serial;  // this is in MyObject's class definition (instance variable)
void MyQObject::func1(void *objData)
{
    MyQObject *obj = static_cast<MyQObject*>(objData);
    obj->serial.clear(QSerialPort::Input);
}
int MyQObject::func2(void *objData)
{
    MyQObject *obj = static_cast<MyQObject*>(objData);
    obj->serial.waitForReadyRead(0);
    return obj->serial.bytesAvailable();
}
void MyQObject::func3(ivoid *objData)
{
    MyQObject *obj = static_cast<MyQObject*>(objData);
    // Read data using serial.read()
}
void MyQObject::func4(void *objData)
{
    MyQObject *obj = static_cast<MyQObject*>(objData);
    // Read data using serial.write()
}

在MyThread的run方法中,我调用了上面的函数。。这导致了崩溃。

错误:

QObject:无法为处于不同线程中的父级创建子级。(父线程是QSerialPort,父线程是QThread,当前线程是OtherThread)

很有可能在obj->serial.waitForReadyRead(0);中创建一个QObject(例如QTimer),该QObject将QSerialPort作为父对象。这可能会造成问题。因此,解决方案可以是找到一种在线程中创建QSerialPort对象的方法。