How do I execute QTcpSocket in a different thread?

2019-04-28 09:46发布

问题:

How do I execute QTcpSocket functions in a different thread?

回答1:

Here is the 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 whatever:

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


回答2:

The QT docs are explicit that the QTCPSocket should not be used accross threads. I.E, create a QTCPSocket in the main thread and have the signal tied to an object in another thread.

I suspect that you are implementing something like a web server where the listen creates a QTCPSocket on the accept. You then want another thread to handle the task of processing that socket. You can't.

The way I worked around it is I kept the socket in the thread it was born in. I serviced all of the incoming data in that thread and threw it into a queue where another thread could work on that data.



回答3:

Put a QMutex lock around all calls, not just on the "different" thread but on all threads. One easy way to do so is via a QMutexLocker



回答4:

What I read in the docs is that QTcpSocket should not be used across threads. If you want to use it in another thread Qt docs say you should create a new QTcpSocket instance in your thread and set the descriptor on the new instance. To do this you need to reimplement QTcpServer and use QTcpServer::incomingConnection. A simple example is provided here.