The problem with the Qt Fortune Threaded Server example is the way it uses threads. As the Qt developers say, “You are doing it wrong”
The problem is QThread inheritance. The QThread class is not really a thread, but the thread controller class and the only reason to inherit it is if you want to change the flow control behavior.
The problem you see is related to thread similarity; to which the object belongs.
If the stream is inherited as follows: -
class FortuneThread : public QThread { Q_OBJECT private: QTcpSocket tcpSocket; };
The FortuneThread object is then created from the main thread: -
FortuneThread* ft = new FortuneThread(parent);
Merging threads for the thread and the objects that it created (tcpSocket) is now the main thread, so tcpSocket is working in the main thread, which indicates an error. The start function is called at the point, the connection is from FortuneThread, but tcpSocket is in the main thread.
The best way to solve this is to create your own class derived from QObject and move it to the stream: -
// Inherit from QObject, not QThread class FortuneSocket : public QObject { Q_OBJECT public slots: void Run(); private: QTcpSocket tcpSocket; }; QThread* pThread = new QThread(parent); FortuneSocket* pFortune = new FortuneSocket(parent); connect(pThread, &QThread::started, pFortune, &FortuneSocket::Run); // Qt5 connect style // move the fortune socket to the thread: - pFortune->moveToThread(pThread);
Now when you start the thread using pThread-> start (), the FortuneSocket object and all its members are working in the new thread.
Using threads in this way also means that you can move multiple objects into one stream, instead of having one object in a stream. Note that creating more threads than CPU cores is pointless!
Finally, there is a more detailed article on how to use QThread, here .