Consumer Producer Problem Code in C++
#include <bits/stdc++.h>
#include<mutex>
#include <unistd.h>
#include <pthread.h>
#include<thread>
using namespace std;
mutex mt;
bool ready=false;
int data=0;
void consumeData(int n){
cout<<"Received Data: "<<n<<endl;
}
int produceData(){
int randomNum= rand()%1000;
cout<<"Produce Data: "<<randomNum<<endl;
return randomNum;
}
void consumer(){
while(true){
while(!ready){
usleep(1000);
}
unique_lock<mutex>ul(mt);
consumeData(data);
ready=false;
}
}
void producer(){
while(true){
unique_lock<mutex>ul(mt);
data=produceData();
ready=true;
ul.unlock();
while(ready){
usleep(1000);
}
}
}
void threadFun(){
mt.lock();
mt.unlock();
mt.lock();
mt.unlock();
}
void consumerThread(){consumer();}
void ProducerThread(){producer();}
int main()
{
thread t1(consumerThread);
thread t2(ProducerThread);
t1.join();
t2.join();
return 0;
}
Online Compiler to Use:https://www.onlinegdb.com/online_c++_compiler
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.