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?
views:
209answers:
1Typically 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.