QThread线程使用

QThread(子线程): 类成员变量如果是指针,无论在run()外部new,还是run()内部new,都可以在start()后,对new的内存进行读写, 唯一注意的是外部和内部同时读写同一块内存容易造成崩溃, 所以使用了QMutex锁。

笔者一般使用QThread线程都是以继承的方式

#ifndef BaseThread_H
#define BaseThread_H

#include <QThread>
#include <QtDebug>
#include <QMutex>

class BaseThread : public QThread
{
    Q_OBJECT
public:
    explicit BaseThread(QObject *parent = 0);
    virtual ~BaseThread();
    //错误返回
    static QString lastError();
    static void setLastError(const QString &lastError);
    //定义线程需要执行任务类型
    int threadType() const;
    void setThreadType(int threadType);
    //返回结果可以自己定义返回值
    int result() const;
    void setResult(int result);
    //是否需要中途跳出线程
    void setNeedStop(bool isNeedStop);
    bool isNeedStop() const;
    //停止线程
    void stopThread();
signals:
    //线程输出
    void sigThreadOut(int threadType);
public slots:
private:
    //线程类型
    int _threadType = 0;
    //线程返回0为正常返回
    int _result = 0;
    //是否停止线程,该变量用于跳出while(!_isNeedStop)循环
    bool _isNeedStop = false;
    //最后错误信息
    static QString _lastError;
    //线程锁,注意return函数中记得解锁
    QMutex _mutex;
};

#endif // BaseThread_H


#include "BaseThread.h"

QString BaseThread::_lastError = "";
BaseThread::BaseThread(QObject *parent) : QThread(parent)
{
}
BaseThread::~BaseThread()
{
//    qDebug()<<"~BaseThread()";

}
void BaseThread::stopThread()
{
    setNeedStop(true);
    this->quit();
    this->wait();
}
bool BaseThread::isNeedStop() const
{
    return _isNeedStop;
}

void BaseThread::setNeedStop(bool isNeedStop)
{
    _isNeedStop = isNeedStop;
}

QString BaseThread::lastError()
{
    return _lastError;
}

void BaseThread::setLastError(const QString &lastError)
{
    _lastError = lastError;
}

int BaseThread::threadType() const
{
    return _threadType;
}

void BaseThread::setThreadType(int threadType)
{
    _threadType = threadType;
}

int BaseThread::result() const
{
    return _result;
}

void BaseThread::setResult(int result)
{
    _result = result;
}

使用方式

这里写代码片
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值