版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012020854/article/details/77481591
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;
}
使用方式
这里写代码片