笔者最近在修改client的scan逻辑,用到了生产消费模型,因此写来写了中这个示例代码。
#include <bits/stdc++.h>
using namespace std;
class BoundedBuffer {
public:
explicit BoundedBuffer(std::size_t size) : begin_(0), end_(0), length_(0) {
container_.resize(size);
}
void Produce(int n) {
std::unique_lock<std::mutex> lck(mutex_);
con_pro_.wait(lck, [&] {
return length_ < container_.size();
});
container_[end_] = n;
end_ = (end_ + 1) % container_.size();
length_++;
con_con_.notify_one();
};
int Consume() {
std::unique_lock<std::mutex> lck(mutex_);
con_con_.wait(lck, [&] {
return length_ > 0;
});
int ret = container_[begin_];
begin_ = (begin_ + 1) % container_.size();
length_--;
con_pro_.notify_one();
return ret;
};
bool empty() const {
return length_ == 0;
}
std::size_t size() const {
return length_;
}
private:
size_t begin_;
size_t end_;
size_t length_;
std::mutex mutex_;
std::condition_variable con_pro_;
std::condition_variable con_con_;
std::vector<int> container_;
};
int main() {
BoundedBuffer buffer(5);
std::vector<std::shared_ptr<std::thread>> produce_jobs;
auto produce_job = [&]() -> void {
for (int i = 0; i < 10; i++) {
buffer.Produce(i);
}
};
produce_jobs.reserve(10);
for (int i = 0; i < 10; i++) {
produce_jobs.emplace_back(std::make_shared<std::thread>(produce_job));
}
while (!buffer.empty()) {
std::cout << buffer.Consume() << std::endl;
}
for (auto &job : produce_jobs) {
job->join();
}
};