c++现在有单一商品,库存上限为10,生产者线程持续不断生产商品,每次生产一个,消费者线程持续不断消费商品,每次消费一个,实现多生产者多消费者demo保证线程安全,并尽可能保证cpu开销最小化
时间: 2024-12-06 21:23:41 浏览: 6
在C++中,我们可以使用`std::mutex`、`std::condition_variable`以及`std::queue`来实现一个多生产者多消费者(MPMC)队列,这种设计通常被称为"互斥量+条件变量"。下面是一个简单的例子:
```cpp
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
class Product {
public:
int id;
};
class Producer : public std::enable_shared_from_this<Producer> {
private:
std::queue<Product>& products;
std::mutex mutex;
std::condition_variable cond;
public:
explicit Producer(std::queue<Product>& queue)
: products(queue), mutex(), cond() {}
void produce() {
for (int i = 0; i < 10; ++i) {
Product product{i};
std::unique_lock<std::mutex> lock(mutex);
products.push(product);
// 消耗信号通知消费者
cond.notify_one();
// 线程休眠一小段时间模拟生产过程
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
};
class Consumer : public std::enable_shared_from_this<Consumer> {
private:
std::queue<Product>& products;
std::mutex& mutex;
std::condition_variable& cond;
public:
explicit Consumer(std::queue<Product>& queue)
: products(queue), mutex(queue.mutex()), cond(queue.cond()) {}
void consume() {
while (true) {
std::unique_lock<std::mutex> lock(mutex);
// 等待产品可用
cond.wait(lock, [] (const std::queue<Product>& q) { return !q.empty(); });
if (!products.empty()) {
Product product = products.front();
std::cout << "Consumed product: ID - " << product.id << std::endl;
products.pop();
} else {
break; // 无更多产品,消费者退出
}
}
}
};
int main() {
std::queue<Product> products;
std::shared_ptr<Producer> producer = std::make_shared<Producer>(products);
std::shared_ptr<Consumer> consumer1 = std::make_shared<Consumer>(products);
std::shared_ptr<Consumer> consumer2 = std::make_shared<Consumer>(products);
std::thread producer_thread(producer->produce);
std::thread consumer1_thread(consumer1->consume);
std::thread consumer2_thread(consumer2->consume);
producer_thread.join();
consumer1_thread.join();
consumer2_thread.join();
return 0;
}
```
在这个示例中,`Producer`负责生产产品并放入队列,`Consumer`从队列中消费产品。`mutex`确保并发访问的线程安全,而`condition_variable`用于线程间的通信。
阅读全文