题目:有生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲区中取走产品进行消费,所有生产者和消费者都是异步方式运行的,但它们必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经装满产品且尚未被取走的缓冲区中投放产品。
假设条件:
1.有5个生产者,每1s生产1件商品
2.有5个消费者,每1s消费1件商品
3.缓冲池大小为5
4.生产者一共生产100件商品后结束
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>
#include <vector>
#include <condition_variable>
using namespace std;
class CThreadDemo
{
private:
std::deque<int> m_data;
std::mutex m_mtx; // 全局互斥锁.
std::condition_variable m_cv; // 全局条件变量.
int m_nGen;
private:
void ProductThread(){
while (true){
std::unique_lock <std::mutex> lck(m_mtx);
m_nGen = ++m_nGen;
while(m_data.size() >=5) {
m_cv.wait(lck);
}
if(m_nGen > 100){
break;
}
cout << "p :" << m_nGen << endl;
m_data.push_back(m_nGen);
lck.unlock();
m_cv.notify_all();
// 等待1S
std::chrono::milliseconds dura(1000);
std::this_thread::sleep_for(dura);
}
}
void ConsumeThread(){
while (true){
std::unique_lock <std::mutex> lck(m_mtx);
if(m_nGen > 100){
break;
}
while (m_data.empty()){
m_cv.wait(lck);
}
int nData = m_data.front();
m_data.pop_front();
cout << "c :" << nData << endl;
lck.unlock();
std::chrono::milliseconds dura(15000);
std::this_thread::sleep_for(dura);
}
}
public:
CThreadDemo(){
m_data.clear();
m_nGen = 0;
}
void Start(){
std::vector<std::thread> threads;
threads.clear();
for (int i = 0; i < 5; i++){// 生产者线程
threads.push_back(std::thread(&CThreadDemo::ProductThread, this));
}
for (int i = 5; i < 10; i++){// 消费者线程
threads.push_back(std::thread(&CThreadDemo::ConsumeThread, this));
}
for (auto& t : threads){// 等待所有线程的退出
t.join();
}
}
};
int main(int argc, char **argv)
{
CThreadDemo test;
test.Start();
return 0;
}