如何在Qt中的线程之间共享QObjects
How to share QObjects between threads in Qt
我对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对象的方法。
相关文章:
- 在cuda线程之间共享大量常量数据
- 线程之间的布尔停止信号
- 线程之间的实时数据共享
- 线程之间的通信不起作用 - C++
- 简单使用 std::atomic 在两个线程之间共享数据
- 不同线程之间的互斥锁同步
- 多个线程之间的获取-释放内存顺序
- 如何在两组线程之间正确来回传输控制权
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 填充和保存线程之间的共享缓冲区
- 在C 中共享线程之间的列表
- 在 API 和应用程序线程之间共享数据
- 将线程之间的标准输入/输出重定向
- Boost::线程如何在主线程和工作线程之间同步
- std::线程之间的互斥体同步
- C++ - 多线程 - 线程之间的通信
- Qthread char阵列在两个线程之间传递后被摧毁
- 线程之间类的静态数据共享
- 增强ASIO和线程之间的消息传递
- 将数组分配在固定数量的线程之间