views:

179

answers:

3

How do I execute QTcpSocket functions in a different thread?

+1  A: 

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

MSalters
+1  A: 

Hi. 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();
mosg
+3  A: 

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.

Michael