目标
目前有5个生产步骤, 1 半导体, 2 芯片, 3 外壳, 4包装, 5销售
如何写一段代码, 使得生产线可以按顺序生产
代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
// 定义产线编号
enum class ProductionLine { Semiconductor, Chip, Case, Shipping, Sales };
// 定义共享资源
std::mutex mtx;
std::condition_variable cv;
int semiconductors = 0;
int chips = 0;
int cases = 0;
bool readyToShip = false;
// 生产线函数
void produce(ProductionLine line) {
while (true) {
// std::cout << "1是" << semiconductors << "-" << "2是" << chips << "-" << "3是" << cases << std::endl;
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [line]() {
switch (line) {
case ProductionLine::Semiconductor:
return semiconductors == 0;
case ProductionLine::Chip:
return semiconductors > 0 && chips == 0;
case ProductionLine::Case:
return semiconductors > 0 && chips > 0 && cases == 0;
default:
return false;
}
});
// 生产
switch (line) {
case ProductionLine::Semiconductor:
std::cout << "Producing semiconductors." << std::endl;
semiconductors++;
break;
case ProductionLine::Chip:
std::cout << "Producing chips." << std::endl;
chips++;
break;
case ProductionLine::Case:
std::cout << "Producing cases." << std::endl;
cases++;
break;
default:
break;
}
// 检查是否所有部件都已生产完毕
if (semiconductors > 0 && chips > 0 && cases > 0) {
std::cout << "生产完毕" << std:: endl;
readyToShip = true;
}
cv.notify_all();
// 解锁互斥锁,让其他线程可以继续运行
lock.unlock();
}
}
// 发货和销售函数
void shipAndSell() {
while (true) {
std::cout << "进入销售" << std:: endl;
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []() { return readyToShip; });
// 发货
std::cout << "Shipping the product." << std::endl;
readyToShip = false;
semiconductors--;
chips--;
cases--;
// 通知其他线程可以继续生产
cv.notify_all();
// 解锁互斥锁,让其他线程可以继续运行
lock.unlock();
// 假设销售是一个简单的打印消息
std::cout << "Product sold." << std::endl;
}
}
int main() {
// 创建生产线程
std::thread producer1(produce, ProductionLine::Semiconductor);
std::thread producer2(produce, ProductionLine::Chip);
std::thread producer3(produce, ProductionLine::Case);
// 创建发货和销售线程
std::thread shipperAndSeller(shipAndSell);
// 等待所有线程完成
producer1.join();
producer2.join();
producer3.join();
shipperAndSeller.join();
return 0;
}