Infovision Labs
Process synchronization like pipe, fifo, fork, mmap , vfork etc.
Producer- consumer problem (coding)
#include <mutex>
#include <memory>
#include <iostream>
#include <thread>
#include <string>
using namespace std;
#define NA -128
int queue[50] = {NA};
int index = 0;
int front_index =0;
std::mutex m;
void consumer()
{
while(1)
{
unique_lock<std::mutex> lck(m);
if(front_index >= 0)
{
// then consume
front_index++;
std::cout << queue[front_index] <<endl;
queue[front_index] = NA;
}
else
{
break;
}
}
}
void producer()
{
while(1)
{
unique_lock<std::mutex> lck(m);
// wait for input
// then produce
for(int i=0; i < 10; i++)
{
cin >> data;
if(front_index <= index && index <50)
{
index++;
queue[index] = data;
}
else
{
front_index =0;
index= 0;
break;
}
}
// index = 10
}
}
int main()
{
thread th1(consumer);
thread th2(producer);
return 0;
}
Comments
Post a Comment