How to execute QTcpSocket in another thread?

How to execute QTcpSocket functions in another thread?

+5
c ++ multithreading qt qt4 tcp
source share
4 answers

Here is an example:

file thread.h:

class Thread : public QThread { Q_OBJECT public: Thread(); protected: void run(); } 

file thread.cpp:

 Thread::Thread() {} void Thread::run() { // do what ever you want with QTcpSocket } 

in main.cpp or something else:

 Thread *myThread = new Thread; connect(myThread, SIGNAL(finished()), this, SLOT(on_myThread_finished())); myThread->start(); 
-2
source share

The QT docs are clear that QTCPSocket should not be used in streams. IE, create a QTCPSocket in the main thread and bind the signal to an object in another thread.

I suspect that you are implementing something like a web server where the listener creates a QTCPSocket upon acceptance. Then you want another thread to handle the processing task of this socket. You can not.

As I worked around, I kept the socket in the stream in which it was born. I served all incoming data in this thread and threw it into a queue where another thread could work on this data.

+6
source share

Put a QMutex lock around all calls, not just on β€œdifferent” threads, but on all threads. One easy way to do this is through QMutexLocker

+1
source share

What I read in the docs is that QTcpSocket should not be used in threads. If you want to use it in another thread, Qt tells you to create a new instance of QTcpSocket in your thread and set the handle to the new instance. To do this, you need to override QTcpServer and use QTcpServer :: incomingConnection . A simple example is presented here .

0
source share

All Articles