Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move QTcpSocket to a new Thread after the connection is initiated

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?

like image 967
Damien Avatar asked Jul 06 '16 06:07

Damien


1 Answers

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.

like image 87
evilruff Avatar answered Oct 14 '22 20:10

evilruff