PDA

View Full Version : parent is in different QThread?



Cruz
5th April 2010, 18:52
Hello!

I have a small issue, obviously with a QThread. It's about a very simple UDP server that periodically sends out a test string. It does the job, but when I start it, it gives me a an error message and I don't understand what's wrong. Can anyone please explain me? Here is the code:



#include <QtCore>
#include <QCoreApplication>
#include "UDPTestServer.h"

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

UDPTestServer udp;
udp.start();

return a.exec();
}




#include <QThread>
#include <QUdpSocket>

class UDPTestServer : public QThread
{
public:
UDPTestServer();
virtual ~UDPTestServer();
void run();

private:
QUdpSocket udpSocket;
};

void UDPTestServer::run()
{
while (true)
{
QByteArray datagram = "Broadcast message";
int bytes = udpSocket.writeDatagram(datagram.data(), datagram.size(), QHostAddress::LocalHost, 7755);
sleep(1);
}
}


I can compile and start it and it does start sending out the "Boradcast message". However, it also prints the error message:



QObject: Cannot create children for a parent that is in a different thread.
(Parent is QUdpSocket(0x22ff48), parent's thread is QThread(0x3e3988), current thread is QThread(0x22ff40)


What does it exactly mean?

I tried moving the call to start() the UDP thread to the constructor of UDPTestServer, but that doesn't make a difference.

Thanks
Cruz

borisbn
5th April 2010, 20:14
1. what is an implementation of UDPTestServer::UDPTestServer() ?
2. try to do:


UDPTestServer::UDPTestServer()
{
moveToThread( this );
}

3. try to create QUdpSocket by pointer. e.g.


QUdpSocket * udpSocket;
...
UDPTestServer::UDPTestServer()
{
moveToThread( this );
udpSocket = new QUdpSocket();
}
UDPTestServer::~UDPTestServer()
{
delete udpSocket;
}

Cruz
5th April 2010, 21:54
My implementation of the constructor is currently empty.

Unfortunately, none of the proposed methods changes anything. I still see the warning when I start the program.

What did work was when I moved the QUdpSocket from being a member of the UDPTestServer class to be a local variable in the run() method of the UDPTestServer. I can see how the constructor of UDPTestServer is executed in the main thread, while the run() method is on UDPTestserver's own thread. So basicly the UDP socket was created in a different thread than where the writeDatagram method is called. But it's still very unclear to me at what point I tried to create children of a parent. And also, why is it not ok to create the UDP socket in one thread and call writeDatagram in another?

faldzip
5th April 2010, 22:10
Make your:

QUdpSocket udpSocket;
a local variable in UDPTestServer::run() instead of member variable. The code is "in new thread" only in run() method implementation so your udpSocket variable belongs to the main thread, and probably it wants to create some objects in writeDatagram() which is called in new thread (different then udpSocket thread).