How to send data from one thread to another thread using Signals and slots mechanism?
-
I have searched a lot on the internet about this topic but I could not find a proper solution. So here are my requirements:
I would be creating two threads - GUI Thread and another worker thread. In the worker thread, I will be using Posix UDP function i.e. "recvFrom()". My intention is to handle the blocking call "recvFrom()" in the worker thread while my GUI thread will be responsive. Everything is fine but my only issue here is to find a way to send data (specifically structure within a structure) to between the threads. Also, I am creating the worker thread that will be a Posix thread but not QThread.- How should I go about creating a Posix Thread but still use only "signal". I hope event loop is not required for worker thread.
- If I create a posix thread how can I use "connect" method as the parameters require objects?
- Is it a good idea to think about implementing the "data transfer" between threads using PostEvent instead of signals and slots mechanism?
-
Hi and welcome to devnet,
Out of curiosity, why not use QUdpSocket and forget about threading since it's asynchronous ?
-
Hi and welcome to devnet,
Out of curiosity, why not use QUdpSocket and forget about threading since it's asynchronous ?
@SGaist I have got a lot of processing to do. So, to avoid the "glitching" effect I am using two threads. Posix UDP because I am forced to use it.
-
In that case why not use a more classic approach of producer/consumer so you simplify your design ?
-
@activeLearner said in How to send data from one thread to another thread using Signals and slots mechanism?:
How should I go about creating a Posix Thread but still use only "signal". I hope event loop is not required for worker thread.
For things to be asynchronous and run in a separate thread you would need the signal/slot connection to be a QueuedConnection (DirectConnection is like a function call (or rather a callback function) and takes place in context (and thus thread) of the caller). A queued connection means that the call to the slot (together with the parameters) is queued in the event loop of the receiver thread.
So, the short answer to this part of your question: Yes, an event loop is required for the worker thread. Since you have to use Posix threads you should look for other solutions than signals/slots for the communication between the threads.
Since you already mentioned UDP, you could have a separate Qt thread running which handles UPD communication between the Qt part of your application and the worker thread. Write a class with the slots you need to send data and handles the translation to your UDP communication. From the GUI thread you can then use signals to call the slots of your new class in the separate Qt thread (which should have an event loop).