#include <iostream>
#include <mutex>
#include <thread>
#include<condition_variable>
#include<deque>
using namespace std;
std::mutex m1;
std::condition_variable cv;
deque<int>buffer;
const unsigned int maxbuffersize=100;
void consumer()
{
int x;
while(true)
{
std::unique_lock<mutex> ul(m1);
cv.wait(ul,[](){return buffer.size()>0;});
if (buffer.size()!=0)
{
x = buffer.back();
buffer.pop_back();
cout<<"Consumer number : "<<x;
}
ul.unlock();
cv.notify_one();
}
}
void producer(int x)
{
while(x)
{
std::unique_lock<mutex> ul(m1);
cv.wait(ul,[](){return buffer.size()<=maxbuffersize;});
buffer.push_back(x);
x--;
cout<<"Producer number : "<<x;
ul.unlock();
cv.notify_one();
}
}
int main() {
thread t1(producer,50);
thread t2(consumer);
t1.join();
t2.join();
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: