问题描述: 1)生产者进程每次生产1个产品(产品数量大于4时停止生产); 2)消费者进程每次消耗2个产品;
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex mu;
std::condition_variable cond;
void ProduceThread(int *productNum)
{
while (true) {
std::unique_lock<std::mutex> lock(mu);
if (*productNum >= 4) {
cout << "store is full cannot produce more." << endl;
cond.wait(lock);
}
cout << "producing...." << endl;
*productNum += 1;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
cout << "A product was produced. current productNum:" << *productNum << endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
cond.notify_one();
lock.unlock();
}
}
void ConsumeThread(int *productNum)
{
while (true) {
std::unique_lock<std::mutex> lock(mu);
if (*productNum <= 1) {
cout << "product is not enough" << endl;
cond.wait(lock);
}
cout << "consuming...." << endl;
*productNum -= 2;
std::this_thread::sleep_for(std::chrono::milliseconds(250));
cout << "2 products consumed." << endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
cond.notify_one();
lock.unlock();
}
}
int main()
{
int products = 3;
std::thread proThread(ProduceThread, &products);
std::thread conThread(ConsumeThread, &products);
proThread.join();
conThread.join();
while (true) {}
return 0;
}
|