The Bounded-Buffer problem, also known as the producer-consumer problem, can be easily solved using the semaphore. In C++, there are no semaphores, but we can use the condition variable instead.
#include <thread> #include <mutex> #include <condition_variable> using namespace std; class BoundedBuffer{ private: deque<int> buffer; int size=10; mutex m; condition_variable cv; public: BoundedBuffer(){}; void produce(int num){ unique_lock<mutex> lock(m); cv.wait(lock,[this](){return buffer.size()<size;}); buffer.push_back(num); cout << "produce " << num << '\n'; cv.notify_all(); } int consume(){ unique_lock<mutex> lock(m); cv.wait(lock,[this](){return buffer.size()>0;}); int res=buffer.front(); buffer.pop_front(); cout << "consume " << res << '\n'; cv.notify_all(); return res; } }; int main(){ BoundedBuffer bf; auto producer=[&](){ for (int i=0;i<5;++i) bf.produce(i); }; auto consumer=[&](){ for (int i=0;i<5;++i) bf.consume(); }; thread producer_thread(producer); thread consumer_thread(consumer); producer_thread.join(); consumer_thread.join(); return 0; }
Reference
https://codereview.stackexchange.com/questions/84109/a-multi-threaded-producer-consumer-with-c11