跳至主要內容

05.QT多线程

约 428 字大约 1 分钟

创建一个简单的线程

继承 QThread 类。
重写 run() 方法。
使用 start() 启动线程
#include <QCoreApplication>
#include <QThread>
#include <QDebug>

// 继承 QThread
class MyThread : public QThread {
public:
    void run() override {
        // 线程执行的任务
        qDebug() << "Thread started!";
        for (int i = 0; i < 5; ++i) {
            qDebug() << "Processing in thread:" << i;
            QThread::sleep(1);  // 模拟耗时操作
        }
        qDebug() << "Thread finished!";
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 创建线程对象
    MyThread thread;

    // 启动线程
    thread.start();

    // 等待线程执行完毕
    thread.wait();

    return a.exec();
}

使用 QObject 和 QThread 实现线程

创建一个普通的 QObject 类,并将任务放到 run() 或者槽方法中。
使用 moveToThread() 将 QObject 对象移动到一个新的线程中。
使用信号和槽机制与主线程或其他线程通信。
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QObject>

class Worker : public QObject {
    Q_OBJECT
public slots:
    void doWork() {
        qDebug() << "Worker thread started!";
        for (int i = 0; i < 5; ++i) {
            qDebug() << "Processing in worker thread:" << i;
            QThread::sleep(1);
        }
        qDebug() << "Worker thread finished!";
        emit finished();  // 发出信号,表示工作完成
    }

signals:
    void finished();  // 线程完成信号
};

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 创建一个线程
    QThread thread;

    // 创建一个 Worker 对象
    Worker worker;

    // 将 Worker 移动到新线程中
    worker.moveToThread(&thread);

    // 连接信号和槽
    QObject::connect(&thread, &QThread::started, &worker, &Worker::doWork);
    QObject::connect(&worker, &Worker::finished, &thread, &QThread::quit);
    QObject::connect(&worker, &Worker::finished, &worker, &QObject::deleteLater);
    QObject::connect(&thread, &QThread::finished, &thread, &QObject::deleteLater);

    // 启动线程
    thread.start();

    return a.exec();
}

#include "main.moc"

控制线程的同步和互斥

#include <QCoreApplication>
#include <QThread>
#include <QMutex>
#include <QDebug>

QMutex mutex;

class Worker : public QThread {
public:
    void run() override {
        mutex.lock();  // 加锁
        qDebug() << "Worker thread started!";
        for (int i = 0; i < 5; ++i) {
            qDebug() << "Processing:" << i;
            QThread::sleep(1);
        }
        qDebug() << "Worker thread finished!";
        mutex.unlock();  // 解锁
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    Worker thread1;
    Worker thread2;

    thread1.start();
    thread2.start();

    thread1.wait();
    thread2.wait();

    return a.exec();
}