仓库用于存储生产好的产品,用循环数组来实现
- 生产者:多个生产者之间互斥,当仓库满时等待,否则将生产好的产品放入仓库
- 消费者:多个消费者之间互斥,当仓库空时等待,否则从仓库拿出一个产品进行消耗
#include <iostream>
#include <mutex>
#include <thread>
#ifdef _MSC_VER
#include <windows.h>
#else
#include <unistd.h>
#endif
void mySleep(int milliseconds) {
#ifdef _MSC_VER
Sleep(milliseconds);
#else
sleep(milliseconds);
#endif
}
const int kProduceItems = 20;
const int kRepositorySize = 5;
template<class T>
class Repository {
public:
T items_buff[kRepositorySize];
std::mutex mtx;
std::mutex produce_mutex;
std::mutex consume_mutex;
std::condition_variable repo_not_full;
std::condition_variable repo_not_empty;
size_t produce_item_count;
size_t consume_item_count;
size_t produce_position;
size_t consume_position;
Repository() {
produce_item_count = 0