Qt中采用多线程实现Socket编程


      本文介绍的是Qt中采用多线程Socket编程,由于工作项目的需要,使用Qtsocket编程。Qt里的example是个不错的教程,但是当我把代码移植到多线程的环境时就出问题了:
QObject: Cannot create children for a parent that is in a different thread.

由于想要在线程中保留一个socket,以便维持双边通信,因此定义如下:

SocketThread:public QThread

{

....

private:

QTcpSocket _tcpSocket;

}

但是这段代码并无法正常的完成工作,后来在网上搜了一下资料,找到以下解释(忘了出处了,以下是中文的大概意思):“ 在QThread中定义的所有东西都属于创建该QThread的线程。“

问题出来了,如果按照这个定义,在SocketThread中定义的_tcpSocket,其实是属于mainThread(SocketThread是在main函数中创建),而当我们在SocketThread中的run函数使用到_tcpSocket的时候,其实是跨线程调用,这样就会出现上面的异常。

解决方法: 需要对SocketThread的定义做一下更改:
SocketThread:public QThread  

 ....  
 private:  
 QTcpSocket* _tcpSocket;  
 }  

在上面我们并没有创建具体的对象,而是定义了一个指针,而如何让指针内的内容从属于SocketThread这个线程呢?答案就是要在SocketThread的run方法中初始化  
SocketThread::run()

 ... ;  
 _tcpSocket = new QTcpSocket();  

进行以上修改之后上面的异常就不再出现了。

      但如果在run()函数中,创建_tcpSocket后,进行相应的信号与槽连接,如
    connnect(_tcpSocket, SIGNAL(readyRead), this, SLOT(slot_read());
    this->exec();
    最后进入事件循环;这时,此套接字有可读的消息,则同样的会发生跟上面类似的错误:
QObject: Cannot create children for a parent that is in a different thread.

(Parent is QNativeSocketEngine(0x1f5f9e8), parent's thread is MyThread(0x1f972c8), current thread is QThread(0x717868)
    为解决这个问题,修改连接函数如下:
  connnect(_tcpSocket, SIGNAL(readyRead), this, SLOT(slot_read(), Qt::DirectConnection);
    具体解释,详见手册,
Qt::AutoConnection  (default) Same as DirectConnection, if the emitter and receiver are in the same thread. Same as QueuedConnection, if the emitter and receiver are in different threads.

Qt::QueuedConnection  The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诺水城子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值