Qt——多线程间的互斥

1.示例:消费者和生产者问题

消费者消费一个产品,生产者生产一个产品

复制代码
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QString>

static QString g_store;

class Producer : public QThread
{
protected:
    void run()
    {
        int count = 0;
        while(true)
        {
            g_store.append(QString::number((count++) % 10));

            qDebug() << objectName() << ":" + g_store;

            msleep(1);
        }
    }
};

class Customer : public QThread
{
protected:
    void run()
    {
        while(true)
        {
            if( g_store != "")
            {
                g_store.remove(0, 1); //去除第一个元素
                qDebug() << objectName() << ":" + g_store;
            }
            msleep(1);
        }

    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Producer p;
    Customer c;

    p.setObjectName("Producer");
    c.setObjectName("Customer");

    p.start();
    c.start();

    return QCoreApplication::exec();
}

但是当消费者和生产者同时访问g_store时,就会产生竞争,程序会崩溃

2.临界资源:每次只允许一个线程进行访问(读/写)的资源

线程间的互斥(竞争):多个线程在同一时刻都需要访问临界资源

QMutex类是一把线程锁,保证线程间的互斥,利用线程锁能够保证临界资源的安全性

3.QMutex中的关键成员函数

  • void lock() 当锁空闲时,获取锁并继续执行;当锁被获取,阻塞并等待锁释放

  • void unlock() 释放锁(同一把锁的获取和释放锁必须在同一线程中成对出现)

    #include
    #include
    #include
    #include
    #include

    static QString g_store;
    static QMutex g_mutex;

    class Producer : public QThread
    {
    protected:
    void run()
    {
    int count = 0;
    while(true)
    {
    g_mutex.lock();
    g_store.append(QString::number((count++) % 10));

    复制代码
              qDebug() << objectName() << ":" + g_store;
              
              g_mutex.unlock();
              msleep(1);
          }
      }

    };

    class Customer : public QThread
    {
    protected:
    void run()
    {
    while(true)
    {
    g_mutex.lock();
    if( g_store != "")
    {
    g_store.remove(0, 1); //去除第一个元素
    qDebug() << objectName() << ":" + g_store;
    }
    g_mutex.unlock();
    msleep(1);
    }

    复制代码
      }

    };

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    复制代码
      Producer p;
      Customer c;
    
      p.setObjectName("Producer");
      c.setObjectName("Customer");
    
      p.start();
      c.start();
    
      return QCoreApplication::exec();

    }

相关推荐
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁2 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超2 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int2 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
慧都小项2 天前
当边缘AI上产线:QtitanDocking 如何让工业 HMI 实现多视图协同
人工智能·qt·ui·边缘计算·qt6.3
CoderYanger2 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读2 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
CCCCCCCCharlie2 天前
Linux进程控制四大核心操作
linux·开发语言