QMutex QMutexLocker简单实例应用

本文介绍Qt中QMutex的使用方法,包括线程间的访问顺序化、互斥量的锁定与解锁机制,以及QMutexLocker类简化互斥量操作的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Qt help 上面的解释是:

QMutex类提供的是线程之间的访问顺序化。

QMutex的目的是保护一个对象、数据结构或者代码段,所以同一时间只有一个线程可以访问它。(在Java术语中,它和同步关键字“synchronized”很相似)。例如,这里有一个方法打印给用户两条消息:

  void someMethod()
  {
     qDebug("Hello");
     qDebug("World");
  }
  

如果同时在两个线程中调用这个方法,结果的顺序将是:

  Hello
  Hello
  World
  World
  

如果你使用了一个互斥量:

  QMutex mutex;

  void someMethod()
  {
     mutex.lock();
     qDebug("Hello");
     qDebug("World");
     mutex.unlock();
  }
  

用Java的术语,这段代码应该是:

  void someMethod()
  {
     synchronized {
       qDebug("Hello");
       qDebug("World");
     }
  }
  

然后同一时间只有一个线程可以运行someMethod并且消息的顺序也一直是正确的。当然,这只是一个很简单的例子,但是它适用于任何需要按特定频率发生的情况。

但你在一个线程中调用lock(),其它线程将会在同一地点试图调用lock()来阻塞,知道这个线程调用unlock()之后其它线程才会获得这个锁。lock()的一种非阻塞选择是tryLock()。

----------------------------------------------------------------------------------------------------------------------------------------------------------

实例1、:代码引用Qt多线程编程总结

#include "dialog.h"
#include <QApplication>
#include <Qthread>
#include <QTextStream>
#include <QMutex>
#include <QDebug>
#include <time.h>
#include <process.h>
#include "windows.h"
#include "winbase.h"
#include "winerror.h"
#include <iostream>

using namespace std;
class MyThreadA : public QThread {
public:    virtual void run();};

class MyThreadB: public QThread {
public:    virtual void run();
};
QMutex mutex;
int number=6;
void MyThreadA::run(){
    qDebug()<<"111"<<endl;
    mutex.lock();
    number *= 5;
    sleep(1);
    number /= 4;
    mutex.unlock();
    qDebug()<<"22"<<endl;
}

void MyThreadB::run(){
     qDebug()<<"33"<<endl;
    mutex.lock();
    number *= 3;
    sleep(1);
    number /= 2;
    mutex.unlock();
    qDebug()<<"44"<<endl;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MyThreadA a;
    MyThreadB b;
    a.start();
    b.start();
//    a.wait();//为了等线程执行结束
//    b.wait();
     Sleep(5000);
     qDebug()<<QString::number(number,10)<<endl;
     return app.exec();
}

 执行结果可以看到,线程a运行,线程B也几乎同时启动,但是线程B等待线程A结束释放lock才执行,实现保护全局变量number不会被线程b改变的作用。

实例2、自动解锁机制QMutexLocker

  • QMutexLocker ( QMutex * mutex )
  • ~QMutexLocker ()
  • QMutex * mutex () const//Returns a pointer to the mutex that was locked in the constructor
  • void relock ()//Relocks an unlocked mutex locker
  • void unlock ()//Unlocks this mutex locker. You can use relock() to lock it again. It does not need to be locked when destroyed

我们学习QMutex可以知道对互斥量的操作很繁琐,并且出错了调试很麻烦,我们使用这个类就能很好的避免这个问题。

改造几句代码

#include "dialog.h"
#include <QApplication>
#include <Qthread>
#include <QTextStream>
#include <QMutex>
#include <QDebug>
#include <time.h>
#include <process.h>
#include "windows.h"
#include "winbase.h"
#include "winerror.h"
#include <iostream>
#include <QMutexLocker>
using namespace std;
class MyThreadA : public QThread {
public:
    virtual void run();
};

class MyThreadB: public QThread {
public:
    virtual void run();
};
QMutex mutex;
int number=6;
void MyThreadA::run(){
    qDebug()<<"111"<<endl;
//    mutex.lock();
    QMutexLocker locker(&mutex);
    number *= 5;
    sleep(1);
    number /= 4;
//    mutex.unlock();
    qDebug()<<"22"<<endl;
}
void MyThreadB::run(){
     qDebug()<<"33"<<endl;
 //   mutex.lock();
    QMutexLocker locker(&mutex);
    number *= 3;
    sleep(1);
    number /= 2;
 //   mutex.unlock();
    qDebug()<<"44"<<endl;
}
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MyThreadA a;
    MyThreadB b;
    a.start();
    b.start();
//    a.wait();//为了等线程执行结束
//    b.wait();
     Sleep(5000);
     qDebug()<<QString::number(number,10)<<endl;
     return app.exec();
}

执行结果是一样的。因为QMutexLocker 申请的这个lock变量在这个函数退出时,自动的调用析构函数来解锁。

#ifndef DATAPOOL_H #define DATAPOOL_H #include <QObject> #include <QQueue> #include <QMutex> #include <QMutexLocker> class datapool : public QObject { Q_OBJECT public: //单例访问接口(线程安全版本) static datapool* instance(); //删除拷贝构造和赋值运算符防止多实例问题 datapool(const datapool&)=delete; datapool& operator=(const datapool&) = delete; void addData(const QByteArray &data); QByteArray takeData(); bool isEmpty() const; signals: void dataReceived(); // 数据到达信号 private: explicit datapool(QObject *parent = nullptr);//构造函数私有 static QMutex m_instanceMutex; // 单例实例互斥锁 static datapool* m_instance; // 单例实例指针 QQueue<QByteArray> m_dataQueue; mutable QMutex m_mutex; }; #endif // DATAPOOL_H#include "datapool.h" #include<QDebug> // 静态成员初始化 QMutex datapool::m_instanceMutex; datapool* datapool::m_instance = nullptr; datapool *datapool::instance() { //双重检查锁定模式 if(!m_instance) { QMutexLocker locker(&m_instanceMutex); if(!m_instance) { m_instance=new datapool(); } } return m_instance; } datapool::datapool(QObject *parent) : QObject{parent} { } void datapool::addData(const QByteArray &data) { QMutexLocker locker(&m_mutex); m_dataQueue.enqueue(data); // qInfo()<<data; //这一步也是正常的 emit dataReceived(); // 通知订阅者 } QByteArray datapool::takeData() { QMutexLocker locker(&m_mutex); return m_dataQueue.dequeue(); } bool datapool::isEmpty() const { QMutexLocker locker(&m_mutex); return m_dataQueue.isEmpty(); } 检查一下这个单例设计模式似乎取数据有问题takedata
03-13
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

波塞冬~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值