CPP线程:生产者与消费者的问题
2015-08-22 01:31
543 查看
#include <iostream> #include <thread> #include<condition_variable> #include <mutex> #include<ctime> #include <array> #include <vector> using namespace std; mutex m; condition_variable full,empty; bool flag = true;//标志 消费完了就退出 vector<int>myint(10);//开辟10个元素 int num = 10; void put(int num)//生产 { for (int i = 0; i < num; i++) { unique_lock<mutex>lk(m); while (10<=myint.size()) { empty.wait(lk);//满了就一直等待 } myint.push_back(i);//插入数据 cout << "生产:" <<i<< endl; full.notify_all(); } this_thread::sleep_for(chrono::seconds(3)); flag = false; } void take()//消费 { while (flag) { unique_lock<mutex>lk(m); while (0==myint.size()) { full.wait(lk);//等待 } if (flag)//消费 { cout << myint[myint.size() - 1] <<" ID:"<<this_thread::get_id()<< endl; myint.pop_back(); empty.notify_all(); } } } //多个生产者 对 多个消费者 void main() { //创建消费者 thread t1(take); thread t2(take); thread t3(take); thread s1(put, 10); thread s2(put, 10); t1.join(); t2.join(); t3.join(); cin.get(); } //单个生产者 与 单个消费者 void main() { //创建消费者 thread t1(take); thread t2(take); thread t3(take); thread t4(take); put(10);//生产 t1.join(); t2.join(); t3.join(); t4.join(); cin.get(); }<img src="https://img-blog.csdn.net/20150822013207296?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
相关文章推荐
- 生产者与消费者模型实现
- java多线程(同步与死锁问题,生产者与消费者问题)
- C++之多个生产者与多个消费者的多线程问题
- 【拨云见日系列】---深入理解生产者与 消费者问题
- 信号量同步编程
- python 条件变量 生产者与消费者
- 进程同步
- 【Linux多线程】三个经典同步问题
- Java多线程--生产者与消费者问题
- 自己用Java写的简单生产者与消费者模型
- C语言 线程同步互斥生产者消费者
- 生产者-消费者问题变形
- 生产者与消费者问题
- java 生产者与消费者问题实现
- 架构设计:生产者/消费者模式 第1页:“生产者/消费者模式”介绍
- 线程生产者与消费者
- Java多线程生产者消费者实例
- 线程间通信
- 多线程解决生产者与消费者问题
- 生产者与消费者