support bazel complie this project and format code.

This commit is contained in:
zhangxing
2023-03-30 00:15:11 +08:00
committed by light-city
parent 1f86192576
commit 7529ae3a55
636 changed files with 10025 additions and 9387 deletions

View File

@@ -0,0 +1,8 @@
# please run `bazel run //design_pattern/producer_consumer:producer_consumer`
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "producer_consumer",
srcs = ["producer_consumer.cpp"],
)

View File

@@ -1,16 +1,15 @@
#include <condition_variable>
#include <iostream>
#include <vector>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <unistd.h>
#include <vector>
using namespace std;
const int MAX_NUM = 10000;
class BoundedBuffer
{
class BoundedBuffer {
public:
BoundedBuffer(size_t n) {
array_.resize(n);
@@ -21,7 +20,7 @@ public:
void Produce(int n) {
{
std::unique_lock<std::mutex> lock(mtx_);
//wait for not full
// wait for not full
not_full_.wait(lock, [=] { return pos_ < array_.size(); });
usleep(1000 * 400);
@@ -29,16 +28,16 @@ public:
end_pos_ = (end_pos_ + 1) % array_.size();
++pos_;
cout << "Produce pos:" << pos_ << endl;
} //auto unlock
} // auto unlock
not_empty_.notify_one();
}
int Consume() {
std::unique_lock<std::mutex> lock(mtx_);
//wait for not empty
// wait for not empty
not_empty_.wait(lock, [=] { return pos_ > 0; });
usleep(1000 * 400);
int n = array_[start_pos_];
start_pos_ = (start_pos_ + 1) % array_.size();
@@ -50,6 +49,7 @@ public:
return n;
}
private:
std::vector<int> array_;
size_t start_pos_;
@@ -63,10 +63,9 @@ private:
BoundedBuffer bb(10);
std::mutex g_mtx;
void Producer()
{
void Producer() {
int n = 0;
while(n < 100) {
while (n < 100) {
bb.Produce(n);
cout << "Producer:" << n << endl;
n++;
@@ -75,28 +74,25 @@ void Producer()
bb.Produce(-1);
}
void Consumer()
{
void Consumer() {
std::thread::id thread_id = std::this_thread::get_id();
int n = 0;
do {
n = bb.Consume();
cout << "Consumer thread:" << thread_id << "=====> " << n << endl;
} while(-1 != n);
} while (-1 != n);
bb.Produce(-1);
}
int main()
{
int main() {
std::vector<std::thread> t;
t.push_back(std::thread(&Producer));
t.push_back(std::thread(&Consumer));
t.push_back(std::thread(&Consumer));
t.push_back(std::thread(&Consumer));
for (auto& one : t) {
for (auto &one : t) {
one.join();
}