SoFunction
Updated on 2025-03-05

Introduction to common communication methods for threads in Qt

Project Scenario

In Qt, thread communication is everywhere, and the most core feature is a kind of inter-thread communication, which is safe, reliable and easy to use. In addition, there are several other commonly used methods:

QMutex

Mutex locks can protect shared data access, such as reading and writing to shared data globalCounter, which can ensure uniqueness and security of data.

#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) {
            ();
            ++globalCounter;
            ();
        }
    }
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    Worker worker1, worker2;
    ();
    ();
 
    ();
    ();
 
    qDebug() << "Global counter:" << globalCounter;
 
    return 0;
}

QWaitCondition

Conditional waiting is usually used with QMutex. The essence is to wait for a certain thread to release the mutex before other threads can use it. Event execution conditions are added to avoid multiple threads accessing the same variable at the same time.

#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 {
        ();
        qDebug() << "Producer is producing.";
        ready = true;
        ();
        ();
    }
};
 
class Consumer : public QThread {
protected:
    void run() override {
        ();
        if (!ready) {
            (&mutex);
        }
        qDebug() << "Consumer is consuming.";
        ();
    }
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    Producer producer;
    Consumer consumer;
 
    ();
    ();
 
    ();
    ();
 
    return 0;
}

QSemaphore

Semaphores can control the number of threads accessing a specific resource.

#include &lt;QCoreApplication&gt;
#include &lt;QThread&gt;
#include &lt;QSemaphore&gt;
#include &lt;QDebug&gt;
 
QSemaphore semaphore(3); // The number of resources allowed to be accessed simultaneously 
class Worker : public QThread {
protected:
    void run() override {
        ();
        qDebug() &lt;&lt; "Worker is accessing resource in thread:" &lt;&lt; QThread::currentThread();
        QThread::sleep(1); // Simulation work        ();
    }
};
 
int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
 
    Worker workers[10];
    for (auto &amp;worker : workers) {
        ();
    }
 
    for (auto &amp;worker : workers) {
        ();
    }
 
    return 0;
}

QEvent

Use event queue delivery and processing to achieve communication between threads.

#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;
     = &receiver;
 
    ();
    ();
 
    return ();
}

The above is the detailed content introduced by the commonly used communication methods of threads in Qt. For more information about Qt thread communication, please pay attention to my other related articles!