大家好,又见面了,我是你们的朋友全栈君。
QThread中有start、quit,但是没有pause,那么我们想要实现这个功能。
大概就是这么点内容吧,实现代码如下:
Thread.h
#include <QThread>
#include <atomic>
#include <QMutex>
#include <QWaitCondition>
class Thread : public QThread
{
Q_OBJECT
public:
Thread(QObject *parent = nullptr);
~Thread() override;
enum State
{
Stoped, ///<停止状态,包括从未启动过和启动后被停止
Running, ///<运行状态
Paused ///<暂停状态
};
State state() const;
public slots:
void start(Priority pri = InheritPriority);
void stop();
void pause();
void resume();
protected:
virtual void run() override final;
virtual void process() = 0;
private:
std::atomic_bool pauseFlag;
std::atomic_bool stopFlag;
QMutex mutex;
QWaitCondition condition;
};
Thread.cpp
#include "Thread.h"
#include <QDebug>
Thread::Thread(QObject *parent)
: QThread(parent),
pauseFlag(false),
stopFlag(false)
{
}
Thread::~Thread()
{
stop();
}
Thread::State Thread::state() const
{
State s = Stoped;
if (!QThread::isRunning())
{
s = Stoped;
}
else if (QThread::isRunning() && pauseFlag)
{
s = Paused;
}
else if (QThread::isRunning() && (!pauseFlag))
{
s = Running;
}
return s;
}
void Thread::start(Priority pri)
{
QThread::start(pri);
}
void Thread::stop()
{
if (QThread::isRunning())
{
stopFlag = true;
condition.wakeAll();
QThread::quit();
QThread::wait();
}
}
void Thread::pause()
{
if (QThread::isRunning())
{
pauseFlag = true;
}
}
void Thread::resume()
{
if (QThread::isRunning())
{
pauseFlag = false;
condition.wakeAll();
}
}
void Thread::run()
{
qDebug() << "enter thread : " << QThread::currentThreadId();
while (!stopFlag)
{
process();
if (pauseFlag)
{
mutex.lock();
condition.wait(&mutex);
mutex.unlock();
}
}
pauseFlag = false;
stopFlag = false;
qDebug() << "exit thread : " << QThread::currentThreadId();
}
测试,运行效果:
可以看到暂停时,PauseQThread.exe的CPU使用率为0%
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/140496.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有