QT线程同步

    科技2022-07-15  118

    首先看一下经典的卖票问题,有5个线程同时售卖100张票:

    #ifndef SELLER_H #define SELLER_H #include <QObject> #include <QThread> class Seller : public QThread { Q_OBJECT public: explicit Seller(QObject *parent = nullptr); private: static int tickets; protected: void run(); signals: public slots: }; #endif // SELLER_H #include "seller.h" #include <QDebug> int Seller::tickets=100; Seller::Seller(QObject *parent) : QThread(parent) { } void Seller::run() { while(tickets>0) { tickets--; qDebug()<<"正在销售第"<<tickets<<"张票"<<"线程ID:"<<currentThreadId(); msleep(500); } } const int LENGTH = 5; Seller *thread1; thread1 = new Seller[LENGTH]; for(int i=0;i<=LENGTH-1;i++){ thread1[i].start(); }

    结果发现有一些票被重复售卖了 解决方案:用QMutex给需要同步的地方加锁

    #include "seller.h" #include <QDebug> int Seller::tickets=100; static QMutex mutex; Seller::Seller(QObject *parent) : QThread(parent) { } void Seller::run() { while(tickets>0) { mutex.lock(); if(tickets>0){ tickets--; qDebug()<<"正在销售第"<<tickets<<"张票"<<"线程ID:"<<currentThreadId(); } mutex.unlock(); } }

    使用QMutexLocker

    #include "seller.h" #include <QDebug> int Seller::tickets=100; QMutex mutex1; Seller::Seller(QObject *parent) : QThread(parent) { } void Seller::run() { while(tickets>0) { QMutexLocker lock(&mutex1); if(tickets>0){ tickets--; qDebug()<<"正在销售第"<<tickets<<"张票"<<"线程ID:"<<currentThreadId(); msleep(200); } } }
    Processed: 0.011, SQL: 8