您的位置:首页 > 编程语言 > C语言/C++

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="" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  生产者与消费者