如何在 qthread 和 mainthread 中使用 QObject 以避免“glibc 检测到双重释放或损坏(fasttop):”?
我有一个 qthread,它使用 udp 套接字在循环中写入和读取数据报。 QUDPSocket 在主线程中创建。如何处理将在 QThread 和主线程中使用的 QObject。另外,在主线程中拥有UDP套接字并在qthread中使用它是否可以?
I have a qthread that uses a udp socket to write and read datagrams in a loop. the QUDPSocket is created in the mainthread. How do I handle QObjects that I will use in both the QThread and mainthread. Also is it ok to have the UDP socket in the mainthread and use it in the qthread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,您应该只允许一个线程处理每个 QObject。在这种情况下,您可能希望让 QThread 持有并使用 QUDPSocket,并且主线程永远不会接触它(理想情况下,主线程甚至不应该持有指向 QUDPSocket 的指针,只是为了确保您永远不会忘记并意外地从错误的线程调用了它的方法)。
当您的 QThread 读取一些 UDP 数据时,它可以对其进行任何初始处理,然后通过 QApplication::postEvent() 或通过排队信号/槽连接将数据传递到主线程。
同样,如果您的主线程有一些数据希望作为 UDP 数据包发送出去,那么它不应该直接在 QUDPSocket 对象上调用 write() ;相反,它应该通知 QThread(通过 postEvent() 或排队信号)并让 QThread 处理它。
Typically you should only allow one thread to deal with each QObject. In this case, you would probably want to have your QThread hold and use the QUDPSocket, and the main thread would not ever touch it (ideally the main thread shouldn't even be holding a pointer to the QUDPSocket, just to be sure you never forget and accidentally call a method on it from the wrong thread).
When your QThread reads some UDP data, it can do any initial processing on it, then pass the data to the main thread via QApplication::postEvent() or via a queued signal/slot connection.
Similarly, if your main thread has some data that it would like to be sent out as a UDP packet, it shouldn't call write() on the QUDPSocket object directly; instead it should notify the QThread (via postEvent() or a queued signal) and let the QThread handle it.