views:

209

answers:

1

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?

+2  A: 

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.

Jeremy Friesner
Thx. Only question remaining is where do I instanciate my variables. For example, I use a QByteArray with the readDatagram function, then I need to fill the contents of this QByteArray into structures I made. where do I instantiate those structs so that I can assign them in the Qthread and eventually read them from the main thread?
yan bellavance
I think the easiest and most foolproof way would be to do the following in the QThread, after the QThread has read a UDP packet: QByteArray myByteArray(sizeof(MyStruct), 0); struct MyStruct * structToFill = (struct MyStruct *) myByteArray.data(); structToFill->someDataField = 5; // or whatever data goes here [...] emit myStructReceived(myByteArray); // tell the main thread via queued signalDoing it this way avoids any chance of a memory leak, etc.
Jeremy Friesner
so do I absolutely need to send the data via a signal or can they just reside in the qthread object and be accessed from both threads. (they would of course never access the same data simultaneously)
yan bellavance
You can just keep them in the qthread object and access them from both threads... but if you do that, you'll need to synchronize the access somehow (e.g. with a mutex). Also, making sure the main thread sees every update will be more difficult. (Of course maybe the main thread doesn't need to see every update)
Jeremy Friesner
ok thanks thats what I needed to know.
yan bellavance