Multi-thread Socket programming in Qt

Source: Internet
Author: User

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:

 
 
  1. 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:

 
 
  1. SocketThread:public QThread  
  2.     {  
  3.             ....  
  4.             private:  
  5.                   QTcpSocket _tcpSocket;  
  6.      } 

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:

 
 
  1. SocketThread:public QThread  
  2.     {  
  3.             ....  
  4.             private:  
  5.                   QTcpSocket* _tcpSocket;  
  6.      } 

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:

 
 
  1. SocketThread::run()  
  2.     ... ;  
  3.      _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 !!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.