QUdpSocket and QThread
In my application I need to wait for event on a UDP socket. How can I achive this? Now I had:
subclassed Thread and ovveride run()
call bind(QHostAddress, int)
call wait on a QWaitCondition
bool connected = m_socket->bind(QHostAddress::LocalHost, LOCALPORT);
In MyThread constructor I also connect to readyRead signal
@QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(readData()));@
My questions are:
- Need I really a QWaitCondition (since I want MyThread processes info I think yes)
- Who have to be responsible to wake MyThread? More specifically how do I understand if data are available?
I am really confuse. Could somebody help me ?
ok. As far as I understand the Q*Socket are async but, still, reading from the socket is performed on the UI thread when the signal readyRead is emitted. Is that correct? Is that safe from the performance perspective? Should I read the socket's content in another thread?
If you want a signal/slot to be emitted in a thread from an object, you must be in an execution loop...therefore, you being in a while loop infinitely makes it so that you will never get a signal from the socket the way that you have it.
connect(&m_socket, SIGNAL(readyRead()), this, SLOT(readData()));
// data received, emit signal to main gui thread with the data...or do what ever you want to do
There isn't any error checking...but you should get your signal if data is received. The exec() sets the thread in an execution loop and allows the thread to receive signals from objects created within the thread. You can pop out of the execution loop by calling exit() from your main thread.
Read the docs on the QThreads:
If you really want it to be in a while loop, you also have the other option to use a state machine in which calls waitForReadyRead() to check for data and then manipulate accordingly without connecting any signals and slots
Also "You're doing it wrong":http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/ read this article for "recommended use of QThread":http://qt-project.org/wiki/QThreads_general_usage. With the recommended approach many common mistakes especially those affecting signals and slots can be avoided.
I had reading somewhere that moveToThread(this) was not more necessary since Qt 4.7. Thank you both. I will go deeply in the docs you had provided. ty again