// Producer Consumer Problem
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>
#include <condition_variable>
using namespace std;
class Buffer {
std::mutex m;
std::condition_variable cv;
std::deque<int> queue;
const unsigned long size = 1000;
public:
void addNum(int num) {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [this]() { return queue.size() <= size; });
queue.push_back(num);
cout << "Pushed " << num << endl;
lock.unlock();
cv.notify_all();
}
int removeNum() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [this]() { return queue.size()>0; });
int num = queue.back();
queue.pop_back();
cout << "Poped " << num << endl;
lock.unlock();
cv.notify_all();
return num;
}
};
void producer(int val, Buffer& buf) {
for(int i=0; i<val; ++i){
buf.addNum(i);
}
}
void consumer(int val, Buffer& buf){
for(int i=0; i<val; ++i){
buf.removeNum();
}
}
int main() {
Buffer b;
std::thread t1(producer, 1000, std::ref(b));
std::thread t2(consumer, 1000, std::ref(b));
t1.join();
t2.join();
return 0;
}
Just another use of std::ref in main while passing Buffer
object as reference in producer and consumer. If std::ref
not used then this code will not compile.