简单线程[qt]

前言

实现一个简单的线程,可以开始停止。

详述

头文件。

#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;
}

结束语

主要方便后面自己拿来直接用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值