C++11学习生产者消费者

就是有一个东西 有人生产有人用

#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<list>
#include<memory>
using namespace std;
#define MaxSize   5
std::mutex mutx;
std::condition_variable produce, consume;
std::list<int> lst;
//核心是 如果仓库不是空的 消费者可以用 如果不是满的 生产者继续生产
void Produce(int id)
{
while (true)
{
std::this_thread::sleep_for(chrono::milliseconds(666));

std::unique_lock<std::mutex>lk(mutx);
produce.wait(lk, []{return lst.size() != MaxSize; });
cout << "Pro buff now size: " << lst.size() << "\n ";
lst.push_front(id);
consume.notify_all(); 

}

}
void Consume()
{
while (true)
{
std::this_thread::sleep_for(chrono::milliseconds(888));
std::unique_lock<std::mutex>lk(mutx);
consume.wait(lk, []{return lst.size() != 0; });
//cout << "consumer " << this_thread::get_id() << ": ";
lst.pop_back();
cout <<"Con buff now size:"<< lst.size() << '\n';
produce.notify_all();
    
}
}
int  main()
{
std::thread p[5], c[5];
//p[0] = thread(Produce, 1);
for (int i = 0; i < 5; i++)
{
c[i] = thread(Consume);
p[i]=thread(Produce,i);
 

}
for (int i = 0; i < 5; i++){
p[i].join();
c[i].join();
}
std::cout << "end";
cin.get();
}

猜你喜欢

转载自blog.csdn.net/qq_35158695/article/details/79362931