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线程通信的资料请关注脚本之家其它相关文章!

相关文章

  • boost.asio框架系列之socket编程

    boost.asio框架系列之socket编程

    这篇文章介绍了boost.asio框架系列之socket编程,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • C++常用的#include头文件总结

    C++常用的#include头文件总结

    这篇文章主要介绍了C++常用的#include头文件,对初学者理解C++程序设计大有好处的相关资料
    2014-07-07
  • C++语言中std::array的用法小结(神器用法)

    C++语言中std::array的用法小结(神器用法)

    这篇文章主要介绍了C++语言中std::array的用法小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • 基于C++的数据库连接池的实现示例

    基于C++的数据库连接池的实现示例

    本文主要介绍了基于C++的数据库连接池,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-11-11
  • linux中查询dns示例

    linux中查询dns示例

    这篇文章主要介绍了linux中查询dns示例,需要的朋友可以参考下
    2014-04-04
  • 优秀程序员必须知道的20个位运算技巧

    优秀程序员必须知道的20个位运算技巧

    掌握简单的位运算技巧还是必要的,所以今天写这篇文章把我积累的一些位运算技巧分享给大家,这些技巧不会是如求“1的数目”的技巧,是最基本的一行位运算技巧
    2013-09-09
  • C语言实现模拟USB对8bit数据的NRZI编码输出

    C语言实现模拟USB对8bit数据的NRZI编码输出

    今天小编就为大家分享一篇关于C语言实现模拟USB对8bit数据的NRZI编码输出,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • C/C++实现MD5校验学习

    C/C++实现MD5校验学习

    MD5全程Message-Digest Algorithm 5,即消息摘要算法第五版,是属于hash算法的一种,本文主要介绍了如何在C++中实现MD5校验,需要的可以了解下
    2024-03-03
  • C++实现中缀表达式转化为后缀表达式详解

    C++实现中缀表达式转化为后缀表达式详解

    这篇文章主要为大家详细介绍了如何利用C++解决实现中缀表达式转换为后缀表达式的问题,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • 基于MFC实现类的序列化详解

    基于MFC实现类的序列化详解

    序列化是将程序中的对象以一种二进制格式存储到存储设备中(例如文本/数据库等),以实现“永生”或随意“流动”。本文将为大家详细讲讲如何基于MFC实现类的序列化,需要的可以参考一下
    2022-07-07

最新评论