8
votes

I've got a threaded server.

QTcpSocket needs to be created on the thread it needs to be ran on, FI: Qt - Handle QTcpSocket in a new thread by passing the socket descriptor.

My problem is that, I need to have a pool of thread and move the socket on a specific thread AFTER the client has sent a specific token which defines on which thread the socket needs to be.

In other words, I need to read the socket to know on which thread to place it beforehand.

Some idea would be to bind first to a QTcpSocket, read, then send the descriptor to the thread and create another QTcpSocket but the doc says:

Note: It is not possible to initialize two abstract sockets with the same native socket descriptor.

Another solution is to create the socket in a separated thread and then join both thread together, though I don't know if that is possible.

Or perhaps be able to read the socket descriptor on the main thread before calling setSocketDescriptor on the child thread, if that is even possible?

1
out of curiosity, why would you have to make the client tell you on which thread you have to run your QTcpSocket?Mike
specific token which defines on which thread the socket needs to be - I wonder how you can specify which thread the socket needs to be. AFAIK you can't specify thread id when creating a thread. If you wan to specify thread name, you can just call thread-->setObjectName("Name") and this has nothing to do with sockets.rightaway717
why don't you simply do socket->moveToThread(otherthread)?λuser
The dock says it is not allowedDamien
You can look at it as a server of cluster of users. A user can create a cluster or join an existing one. Each cluster has its own thread to improve perfomances and use multi-core.Damien

1 Answers

1
votes

You can absolutely easily move sockets across QThreads, just pay attention to four things:

1) Make sure your QTcpSocket does not have parent before you move

2) Disconnect everything from socket object before move

3) Connect anything you need back in a function which is running in a destination thread (you may use some sort of pool in a thread there those 'moved' objects stored before thread pick them up

4) Call readAll() after init as you may miss some readyRead() signals

Don't see any reasons not to do this if that fits design, at least I used it many times for multithreaded services to split sockets handlers across cores.