Qt中线程常用通信方式介绍

 更新时间:2025年01月15日 08:35:16   作者:雲烟  
Qt中,线程通信无处不在,最核心的特性信号槽就是一种线程间通信,这篇文章主要为大家介绍了几种常用的方式,需要的小伙伴可以参考一下

项目场景

Qt中,线程通信无处不在,最核心的特性信号槽就是一种线程间通信,安全可靠易用。除此之外,还有别的几种常用的方式:

QMutex

互斥锁,可以保护共享的数据访问,例如对共享数据globalCounter得读写,可以保证数据的唯一和安全。

#include <QCoreApplication>
#include <QThread>
#include <QMutex>
#include <QDebug>
 
QMutex mutex;
int globalCounter = 0;
 
class Worker : public QThread {
protected:
    void run() override {
        for (int i = 0; i < 1000; ++i) {
            mutex.lock();
            ++globalCounter;
            mutex.unlock();
        }
    }
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    Worker worker1, worker2;
    worker1.start();
    worker2.start();
 
    worker1.wait();
    worker2.wait();
 
    qDebug() << "Global counter:" << globalCounter;
 
    return 0;
}

QWaitCondition

条件等待通常与QMutex搭配使用,本质是等待某一线程释放mutex后,别的线程才可以使用,添加了事件执行条件,可以避免同一时间多个线程同时访问同一变量。

#include <QCoreApplication>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QDebug>
 
QMutex mutex;
QWaitCondition condition;
bool ready = false;
 
class Producer : public QThread {
protected:
    void run() override {
        mutex.lock();
        qDebug() << "Producer is producing.";
        ready = true;
        condition.wakeOne();
        mutex.unlock();
    }
};
 
class Consumer : public QThread {
protected:
    void run() override {
        mutex.lock();
        if (!ready) {
            condition.wait(&mutex);
        }
        qDebug() << "Consumer is consuming.";
        mutex.unlock();
    }
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    Producer producer;
    Consumer consumer;
 
    consumer.start();
    producer.start();
 
    consumer.wait();
    producer.wait();
 
    return 0;
}

QSemaphore

信号量可以控制访问特定资源的线程数量。

#include <QCoreApplication>
#include <QThread>
#include <QSemaphore>
#include <QDebug>
 
QSemaphore semaphore(3); // 允许同时访问资源的数量
 
class Worker : public QThread {
protected:
    void run() override {
        semaphore.acquire();
        qDebug() << "Worker is accessing resource in thread:" << QThread::currentThread();
        QThread::sleep(1); // 模拟工作
        semaphore.release();
    }
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    Worker workers[10];
    for (auto &worker : workers) {
        worker.start();
    }
 
    for (auto &worker : workers) {
        worker.wait();
    }
 
    return 0;
}

QEvent

使用事件队列传递和处理,实现线程间的通信。

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QEvent>
#include <QApplication>
 
class CustomEvent : public QEvent {
public:
    static const QEvent::Type EventType = static_cast<QEvent::Type>(QEvent::User + 1);
    CustomEvent(const QString &message) : QEvent(EventType), message(message) {}
    QString message;
};
 
class EventReceiver : public QObject {
protected:
    bool event(QEvent *event) override {
        if (event->type() == CustomEvent::EventType) {
            CustomEvent *customEvent = static_cast<CustomEvent *>(event);
            qDebug() << "Received custom event with message:" << customEvent->message;
            return true;
        }
        return QObject::event(event);
    }
};
 
class EventSender : public QThread {
protected:
    void run() override {
        QThread::sleep(1);
        qApp->postEvent(receiver, new CustomEvent("Hello from another thread!"));
    }
public:
    EventReceiver *receiver;
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    EventReceiver receiver;
    EventSender sender;
    sender.receiver = &receiver;
 
    sender.start();
    sender.wait();
 
    return app.exec();
}

以上就是Qt中线程常用通信方式介绍的详细内容,更多关于Qt线程通信的资料请关注脚本之家其它相关文章!

相关文章

  • c语言stack(栈)和heap(堆)的使用详解

    c语言stack(栈)和heap(堆)的使用详解

    这篇文章主要介绍了c语言stack(栈)和heap(堆)的使用详解,需要的朋友可以参考下
    2014-04-04
  • C语言学习之标识符的使用详解

    C语言学习之标识符的使用详解

    C语言标识符是用于表示变量、函数、常量、类型等程序元素的名称,这篇文章将通过一些简单的示例为大家介绍一下C语言标识符的使用,需要的可以参考一下
    2023-05-05
  • C字符串操作函数实现方法小结

    C字符串操作函数实现方法小结

    这篇文章主要介绍了C字符串操作函数实现方法,实例总结了C语言字符串操作的相关技巧,非常具有实用价值,需要的朋友可以参考下
    2015-04-04
  • 基于Opencv实现颜色识别

    基于Opencv实现颜色识别

    这篇文章主要为大家详细介绍了基于Opencv实现颜色识别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-07-07
  • C/C++之I/O性能优化过程

    C/C++之I/O性能优化过程

    C++I/O优化需禁用同步、减少刷新次数、批量处理数据,常用方法包括sync_with_stdio(false)、使用printf/scanf/fread、避免endl、stringstream缓存及文件一次性读取,针对不同场景(算法竞赛、大数据、文本处理)选择合适策略,核心是降低I/O开销与格式转换成本
    2025-09-09
  • 新手socket编程入门详解指南

    新手socket编程入门详解指南

    本文,将一步一步引导初学者来学习socket,所有编程思路都结合在socket API里面,以及提供socket的疑问和基础知识点,同时在最后给出多个例程,下面可以和小编一起学习
    2019-05-05
  • C++11 学习笔记之std::function和bind绑定器

    C++11 学习笔记之std::function和bind绑定器

    这篇文章主要介绍了C++11 学习笔记之std::function和bind绑定器,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-07-07
  • C语言使用mciSendString实现播放音乐功能

    C语言使用mciSendString实现播放音乐功能

    mciSendString 支持 mp3、wma、wav、mid 等多种媒体格式,使用非常简单。这篇文章就来为大家介绍一下C语言如何使用mciSendString实现播放音乐功能,需要的可以参考一下
    2023-02-02
  • 详解c++优先队列priority_queue的用法

    详解c++优先队列priority_queue的用法

    本文详细讲解了c++优先队列priority_queue的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12
  • C语言实现求解最小公倍数的算法示例

    C语言实现求解最小公倍数的算法示例

    这篇文章主要为大家介绍了C语言如何实现求解任意两个正整数的最小公倍数,文中采用了穷举法和定理法。感兴趣的小伙伴快来跟随小编一起学习学习吧
    2021-12-12

最新评论