This article introducesQtMultipleThread SocketProgramming, due to work needs, began to contactQtOfSocketProgramming.QtThe example in is a good tutorial, but when I port the code to multipleThreadThe problem occurs in the environment:
- QObject: Cannot create children for a parent that is in a different thread.
Because you want to retainSocketTo maintain bilateral communication, the definition is as follows:
- SocketThread:public QThread
- {
- ....
- private:
- QTcpSocket _tcpSocket;
- }
However, this code does not work properly. I searched the internet and found the following explanation and forgot the source. Here is the general meaning of Chinese ): "Everything defined in QThread belongs to the thread that created the QThread. "
The problem arises. According to this definition, _ tcpSocket defined in SocketThread actually belongs to mainThreadSocketThread created in main function ), when the run function in SocketThread uses _ tcpSocket, it is actually called across threads, so the above exception will occur.
Solution: modify the definition of SocketThread:
- SocketThread:public QThread
- {
- ....
- private:
- QTcpSocket* _tcpSocket;
- }
We didn't create a specific object above, but defined a pointer. How can we make the content in the pointer belong to the SocketThread thread? The answer is to initialize it in the run method of SocketThread:
- SocketThread::run()
- ... ;
- _tcpSocket = new QTcpSocket();
After making the above changes, the above exceptions will no longer appear.
Summary:QtMultithreadingSocketAfter the introduction of the programming content, we may not be able to contact multithreading during the programming process. I believe we have some knowledge about it. Finally, I hope this article will help you understand it !!!