Qt线程(1)

本文介绍了在Qt线程中使用SocketWorker类遇到的问题及解决方案。通过创建SocketWorker类封装QTcpSocket,讨论了线程安全、信号与槽的连接方式,以及不同实现思路对程序行为的影响。当使用特定的线程连接方式时,出现了主线程被终止但UI未关闭的情况,而调整连接方式后问题得到解决。
摘要由CSDN通过智能技术生成

在PictureBook Connector里初始使用的线程结构为

// SocketThread.h
SocketThread : QThread
{
protected:
    virtual run();
};
// SocketThread.cpp
void SocketThread :: run()
{
    QTcpSocket tcpSocket;
    if(!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }
    // can't connect slot
    // connect(&tcpSocket, SIGNAL(disconnected()), this, SLOT(quit()), Qt::QueuedConnection);
    tcpSocket.moveToThread(this);

    while( !m_quit && tcpSocket.state() == QAbstractSocket::ConnectedState ) {
        // ...
    }
}

因为需求的原因,需要将代码中的connect注释掉的代码打开,以使得在socket断掉的时候可以将thread退出。
但是却发现不能触发信号与槽,在一位同行的介绍下,在QtHelp里看了Multithreading Technologies in Qt。

Lifetime of thread Operation Solution
One call Run a new linear function within another thread, optionally with progress updates du
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值