使用qt6 中QRecursiveMutex,写一个有关static QRecursiveMutex 的例子
时间: 2024-02-17 20:04:22 浏览: 15
好的,以下是一个使用 `static QRecursiveMutex` 的例子:
```cpp
#include <QCoreApplication>
#include <QThread>
#include <QMutex>
#include <QDebug>
static QRecursiveMutex mutex;
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = nullptr) : QObject(parent) {}
public slots:
void doWork()
{
QMutexLocker locker(&mutex);
qDebug() << "Thread" << QThread::currentThread() << "is doing some work.";
QThread::sleep(2);
qDebug() << "Thread" << QThread::currentThread() << "finished the work.";
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Worker worker;
QThread thread1;
QThread thread2;
QObject::connect(&thread1, &QThread::started, &worker, &Worker::doWork);
QObject::connect(&thread2, &QThread::started, &worker, &Worker::doWork);
worker.moveToThread(&thread1);
worker.moveToThread(&thread2);
thread1.start();
thread2.start();
thread1.wait();
thread2.wait();
return a.exec();
}
```
在这个例子中,我们创建了一个 `static QRecursiveMutex mutex`,并在两个线程中使用它来保护 `Worker::doWork()` 方法中的临界区。我们使用 `QMutexLocker` 来自动锁定和解锁互斥量。
注意,`static QRecursiveMutex` 是一个静态成员,这意味着它是在类的所有实例之间共享的。这对于在多个线程中访问共享数据时非常有用,因为它允许多个线程同时访问同一个对象。