线程使用之条件等待模拟生产者消费者
来源:互联网 发布:linux格式化磁盘 编辑:程序博客网 时间:2024/05/22 09:00
producer_customer.h
#include <QThread>class Producer : public QThread{public: Producer();protected: void run();};class Customer : public QThread{public: Customer();protected: void run();};
producer_customer.h
#include "producer_customer.h"#include <QWaitCondition>//等待条件#include <QMutex>#include <QDebug>QWaitCondition cond;QMutex mutex;int global = 0;int flag = 0;Producer::Producer(){}void Producer::run(){ while(1) { mutex.lock(); int tmp = global; global += 2; qDebug()<< currentThreadId() << ", Producer: " << tmp << "-->" << global; //判定标志,是否有人在等待 while(!flag) { mutex.unlock(); usleep(200); mutex.lock(); } cond.wakeAll();//唤醒所有消费者 //cond.wakeOne(); qDebug() << "producer finished! ----------------------"; //只唤醒一个处于等待的消费者 mutex.unlock(); sleep(2); }}Customer::Customer(){}void Customer::run(){ while(1) { mutex.lock(); //++ flag ++; cond.wait(&mutex);//等待生产者唤醒消费 //-- flag --; int tmp = global; global--; qDebug()<< currentThreadId() << ", Customer: " << tmp << "-->" << global; qDebug() << "customer finished!================"; mutex.unlock(); sleep(1); }}
main.cpp
#include <QApplication>#include <QDebug>#include "producer_customer.h"int main(int argc, char *argv[]){ QApplication a(argc, argv); Producer *p = new Producer; Customer *c1 = new Customer; Customer *c2 = new Customer; p->start(); c1->start(); c2->start(); return a.exec();}
阅读全文
0 0
- 线程使用之条件等待模拟生产者消费者
- Qt生产者消费者实验:等待条件QWaitCondition
- Qt生产者消费者实验:等待条件QWaitCondition
- 线程之“生产者消费者”
- 线程之生产者消费者
- 线程之生产者、消费者
- C#线程模拟生产者消费者
- 消费者生产者问题---线程互斥锁+条件变量
- 线程 ,生产者. 消费者 互斥锁,条件变量
- 生产者和消费者之等待唤醒机制
- 多线程-生产者消费者之等待唤醒机制
- 线程同步之生产者消费者
- Java 线程之生产者消费者
- 线程之生产者消费者模型
- Qt生产者消费者实验(2):等待条件QWaitCondition
- Qt生产者消费者实验(2):等待条件QWaitCondition
- Qt生产者消费者实验(2):等待条件QWaitCondition
- 消费者生产者模型-java 线程模拟
- python datetime学习
- 练习31
- CAS单点登陆,URL多出个参数jsessionid导致登陆失败问题
- git-flow
- oracle物化视图的批量更新
- 线程使用之条件等待模拟生产者消费者
- 抢红包算法
- 练习32
- ubuntu命令行直接发送email,带附件
- 独立成分分析简介(ICA)
- hadoop HDFS存储原理
- jQuery 获取页面table指定数据
- Android M 特性大全
- 获取服务器端时间的处理思路和代码 涉及PHP JavaScript Yii