QSemaphore示例

QSemaphore

//Producer.h
//Producer\Customer都继承于QThread
class Producer:public QThread {
        Q_OBJECT
public:
    Producer(){}
protected:
    void run()override;
};

class Customer:public QThread {
        Q_OBJECT
public:
    Customer(){}
protected:
    void run()override;
};

//Producer.cpp
//ProducerSe初始为1,为了使生产者线程启动提供条件。
QSemaphore ProducerSe(1);
QSemaphore CustomerSe;

void Producer::run(){
    for(int i = 0; i < 1000; ++i) {
        ProducerSe.acquire();
        int num = QRandomGenerator::global()->bounded(5);
        qDebug()<<"Producer:"<<QThread::currentThreadId()
                  <<",release source count:"<<num<<"|"
                  <<QDateTime::currentDateTime().toString(Qt::ISODateWithMs);
        CustomerSe.release(num);
        QThread::msleep(3000);
    }
}

void Customer::run(){
    for(int i = 0; i < 1000; ++i) {
        CustomerSe.acquire() ;
        qDebug()<<"Customer:"<<(int*)QThread::currentThreadId()<<"|"
        <<QDateTime::currentDateTime().toString(Qt::ISODateWithMs);
        ProducerSe.release();
    }
}
OUT:
Producer: 0x474c ,release source count: 0 | "2019-09-20T10:27:10.463"
Producer: 0x474c ,release source count: 2 | "2019-09-20T10:27:13.463"
Customer: 0x3914 | "2019-09-20T10:27:13.463"
Customer: 0x6acc | "2019-09-20T10:27:13.463"
Producer: 0x474c ,release source count: 1 | "2019-09-20T10:27:16.463"
Customer: 0x6b94 | "2019-09-20T10:27:16.463"
Producer: 0x474c ,release source count: 1 | "2019-09-20T10:27:19.465"
Customer: 0x3914 | "2019-09-20T10:27:19.465"
Producer: 0x474c ,release source count: 3 | "2019-09-20T10:27:22.477"
Customer: 0x6b94 | "2019-09-20T10:27:22.477"
Customer: 0x4c98 | "2019-09-20T10:27:22.477"
Customer: 0x5190 | "2019-09-20T10:27:22.477"
//生产者每次随机释放消费者锁个数,阻塞的的消费者随机启动释放的个数。
    
//main.cpp
int main(int argc,char **argv) {}
	Producer p;
    p.start();

    QVector<Customer*> vtr;
    for(int i = 0; i < 5; ++i){
        Customer *c = new Customer;
        QObject::connect(c,&Customer::finished,
                         c,&Customer::deleteLater);
        vtr.push_back(c);
        c->start();
    }

    p.wait();

    for(auto item : vtr){
        if(item != nullptr){
            item->wait();
        }
    }

    for(auto &item : vtr){
        if(item != nullptr){
            delete item;
            item = nullptr;
        }
    }
	return 0;
}

你可能感兴趣的:(----Qt多线程)