线程是操作系统能够调用的最小运算单位,包含在进程之中。
1:QThread
在Qt中集成QThread是最为常规的实现线程的方式,此方式易于理解便于操作。只需要重写Run()函数,实现自己的线程工作即可。
#pragma once
#include <QObject>
#include <QThread>
#include <qDebug>
class Qthreadtest : public QThread
{
Q_OBJECT
public:
Qthreadtest(QObject* parent = nullptr);
~Qthreadtest();
protected:
virtual void run() override;
public:
void stopThread();
private:
bool b_stop = false;
};
#include "Qthreadtest.h"
Qthreadtest::Qthreadtest(QObject* parent /*= nullptr*/)
{
}
Qthreadtest::~Qthreadtest()
{
}
void Qthreadtest::run()
{
while (!b_stop)
{
qDebug() << "test";
msleep(500);
}
quit();
}
void Qthreadtest::stopThread()
{
b_stop = true;
}
首先生成Qthreadtest类,然后使用start()进行调用
Qthreadtest m_Qthreadtest = new Qthreadtest(this);
m_Qthreadtest->start();
如果需要退出线程,则执行
m_Qthreadtest->stopThread();
//如果退出程序,则在析构中执行:
m_Qthreadtest->quit();
m_Qthreadtest->wait();
2: moveToThread
所有继承自QObject的类都可以使用moveToThread()将自己的函数功能放到线程中运行。
#include "moveObject.h"
#include <QThread>
moveObject::moveObject(QObject* parent /*= nullptr*/)
:QObject(parent)
{
}
moveObject::~moveObject()
{
}
void moveObject::DoWorks()
{
while (!b_stop)
{
qDebug() << "dddddd";
QThread::sleep(1);
}
}
void moveObject::StopWorks()
{
b_stop = true;
}
#pragma once
#include <QObject>
#include <QDebug>
class moveObject : public QObject
{
Q_OBJECT
public:
moveObject(QObject* parent = nullptr);
~moveObject();
void StopWorks();
public slots:
void DoWorks();
private:
bool b_stop = false;
};
调用:
_moveObject = new moveObject();
moveThrea = new QThread();
_moveObject->moveToThread(moveThrea);
connect(moveThrea, &QThread::started, _moveObject, &moveObject::DoWorks);
moveThrea->start();
退出:
_moveObject->StopWorks();
moveThrea->quit();
moveThrea->wait();
3:QThreadPool
QThreadPool是一个用于关于和调度线程的类。首先创建一个QThreadPool对象,并向线程池提交任务,任务可以是任何实现了QRunable的接口对象。例子如下:
#pragma once
#include <QObject>
#include <QThread>
#include <qDebug>
class Qthreadtest : public QThread
{
Q_OBJECT
public:
Qthreadtest(QObject* parent = nullptr);
~Qthreadtest();
protected:
virtual void run() override;
public:
void stopThread();
private:
bool b_stop = false;
};
#include "Qthreadtest.h"
Qthreadtest::Qthreadtest(QObject* parent /*= nullptr*/)
{
}
Qthreadtest::~Qthreadtest()
{
}
void Qthreadtest::run()
{
while (!b_stop)
{
qDebug() << "test";
msleep(500);
}
quit();
wait();
}
void Qthreadtest::stopThread()
{
b_stop = true;
}
进行调用:
QThreadPool* pool = QThreadPool::globalInstance();
pool->setMaxThreadCount(4);
for (int i = 0; i <= 10; i++)
{
m_RunableTest = new RunableTest();
pool->start(m_RunableTest);
}
结束,销毁线程池
QThreadPool* pool = QThreadPool::globalInstance();
pool->clear();
pool->waitForDone();
delete pool;