QT中的线程同步机制

在 Qt 6.8.2(C++)中,两个线程之间的同步可以通过以下机制实现。以下是常用方法及代码示例:

1. ‌**QMutex(互斥锁)**‌

用于保护共享资源,确保同一时间只有一个线程访问资源。

复制代码
cpp 复制代码
#include <QMutex>
#include <QThread>

QMutex mutex;
int sharedData = 0;

class WorkerThread : public QThread {
protected:
    void run() override {
        mutex.lock();
        sharedData++;
        mutex.unlock();
    }
};

// 使用 QMutexLocker(更安全,自动管理锁)
void safeIncrement() {
    QMutexLocker locker(&mutex);
    sharedData++;
}

2. ‌**QReadWriteLock(读写锁)**‌

允许多个线程同时读取,但写入时独占。

cpp 复制代码
#include <QReadWriteLock>

QReadWriteLock rwLock;
QString sharedString;

class ReaderThread : public QThread {
    void run() override {
        rwLock.lockForRead();
        qDebug() << "Read:" << sharedString;
        rwLock.unlock();
    }
};

class WriterThread : public QThread {
    void run() override {
        rwLock.lockForWrite();
        sharedString = "New Data";
        rwLock.unlock();
    }
};

3. ‌**QSemaphore(信号量)**‌

控制对多个相同资源的访问。

cpp 复制代码
#include <QReadWriteLock>

QReadWriteLock rwLock;
QString sharedString;

class ReaderThread : public QThread {
    void run() override {
        rwLock.lockForRead();
        qDebug() << "Read:" << sharedString;
        rwLock.unlock();
    }
};

class WriterThread : public QThread {
    void run() override {
        rwLock.lockForWrite();
        sharedString = "New Data";
        rwLock.unlock();
    }
};

4. ‌**QWaitCondition(条件变量)**‌

让线程等待某个条件满足后再执行。

cpp 复制代码
#include <QWaitCondition>
#include <QMutex>

QMutex mutex;
QWaitCondition condition;
bool dataReady = false;

// 生产者线程
void Producer::run() {
    mutex.lock();
    dataReady = true;
    condition.wakeAll(); // 唤醒所有等待线程
    mutex.unlock();
}

// 消费者线程
void Consumer::run() {
    mutex.lock();
    while (!dataReady) {
        condition.wait(&mutex); // 释放mutex并等待
    }
    // 处理数据
    mutex.unlock();
}

5. ‌信号槽跨线程通信

Qt 的信号槽机制默认是线程安全的,可通过 QueuedConnection 实现跨线程通信。

cpp 复制代码
// Worker对象在子线程中执行任务
class Worker : public QObject {
    Q_OBJECT
public slots:
    void doWork() {
        // 耗时操作
        emit resultReady(result);
    }
signals:
    void resultReady(int);
};

// 主线程中
QThread thread;
Worker worker;
worker.moveToThread(&thread);
connect(&worker, &Worker::resultReady, this, &MainWindow::handleResult);
thread.start();

// 触发任务
QMetaObject::invokeMethod(&worker, "doWork", Qt::QueuedConnection);

关键注意事项:

  • 线程亲和性 ‌:使用 moveToThread() 将对象移动到目标线程,避免直接跨线程访问成员。
  • 避免死锁 ‌:确保锁的获取和释放成对出现,优先使用 QMutexLocker
  • 跨平台性‌:Qt 的同步机制封装了系统原生 API(如 Windows 的临界区、事件),保证跨平台行为一致。

根据需求选择合适机制:互斥锁适合简单共享资源,信号量控制资源池,条件变量适合复杂等待逻辑,信号槽适合解耦通信。

相关推荐
Felix_One2 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
郑州光合科技余经理10 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12310 天前
matlab画图工具
开发语言·matlab
dustcell.10 天前
haproxy七层代理
java·开发语言·前端
norlan_jame10 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone10 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549610 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月10 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_5312371710 天前
C语言-数组练习进阶
c语言·开发语言·算法