前言
实现一个简单的线程,可以开始停止。
详述
头文件。
#ifndef SIMPLETHREAD_H
#define SIMPLETHREAD_H
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
class SimpleThread : public QThread
{
Q_OBJECT
public:
explicit SimpleThread(QObject *parent = nullptr);
~SimpleThread();
// 线程控制
void startThread();
void stopThread();
bool isRunning() const;
protected:
void run() override;
private:
// 线程控制变量
mutable QMutex m_mutex;
QWaitCondition m_condition;
bool m_stopRequested;
};
#endif // SIMPLETHREAD_H
CPP文件。
#include "SimpleThread.h"
#include <QDebug>
#include <QElapsedTimer>
SimpleThread::SimpleThread(QObject *parent)
: QThread(parent)
, m_stopRequested(false)
{
}
SimpleThread::~SimpleThread()
{
stopThread();
}
void SimpleThread::startThread()
{
QMutexLocker locker(&m_mutex);
if (isRunning()) {
qDebug() << "Thread is already running";
return;
}
m_stopRequested = false;
QThread::start();
qDebug() << "Thread started";
}
void SimpleThread::stopThread()
{
{
QMutexLocker locker(&m_mutex);
m_stopRequested = true;
m_condition.wakeAll(); // 唤醒可能正在等待的线程
}
// 等待线程结束,最多等待3秒
if (isRunning()) {
if (!wait(3000)) {
qWarning() << "Thread did not finish in time, terminating...";
terminate();
wait();
}
qDebug() << "Thread stopped";
}
}
bool SimpleThread::isRunning() const
{
return QThread::isRunning();
}
void SimpleThread::run()
{
qDebug() << "Thread running in thread:" << QThread::currentThreadId();
int counter = 0;
while (true) {
// 检查停止请求
{
QMutexLocker locker(&m_mutex);
if (m_stopRequested) {
break;
}
}
// 模拟工作 - 这里可以替换为实际的任务
{
qDebug() << "counter : " << counter++;
QThread::msleep(1000); // 1ms延迟
}
}
qDebug() << "Thread finished, total iterations:" << counter;
}
结束语
主要方便后面自己拿来直接用。
2899

被折叠的 条评论
为什么被折叠?



