views:

65

answers:

2

I'm building a small multithreaded web server. The QTcpSockets are fetched in the main thread and then hand over by QtConcurrent to the QThreadPool, which eventually processes the data and sends out an answer.

My problem is that the socket is created in the main thread and processed in another one. This causes errors when trying to write to the socket:

socket->write(somedata);

QObject: Cannot create children for a parent that is in a different thread. (Parent is QNativeSocketEngine(0x608330), parent's thread is QThread(0x600630), current thread is QThread(0x505f60)

The clean way would be to move the socket object to the processing thread using

socket->moveToThread(QThread::currentThread()).

This, however, can only be called within the thread the object was created in. Furthermore, the socket has the QTcpServer object as parent, so moveToThread() will fail anyway (parented objects cannot switch threads).

How can I move the object to the QThread::currentThread() within the code that is run by the threadpool? Alternatively, how can I write to a socket outside the thread it was created?

A: 

Hey,

Bradley Hugues wrote a post on the Qt Labs talking about this subject, maybe this will help you a bit !

http://labs.trolltech.com/blogs/2010/06/17/youre-doing-it-wrong/

Andy M
Thanks, I know this post. In fact I'm doing it exactly that way at the moment, but this does not work with a thread pool, which I'd like to use. When you distribute work to multiple threads you end up in programming something like a tread pool anyway, so why don't use the existing one? :)
gre
A: 

Extend QTcpServer, reimplement incomingConnection(int socketDescriptor) and pass the socket descriptor to the threads in the pool. Have the QRunnable create the QTcpSocket from the descriptor and start an event loop to receive that socket's signals.

andref