Você está na página 1de 1

#include <iostream>

#include <thread>
#include <semaphore.h>

using namespace std;

const int n=3;


int c=0;
sem_t libres,mutex,ocupados;
int fin,frente,elemento;
int cola[n];

void productor()
{
while(true){
elemento = rand()%10+1;
sem_wait(&libres);
sem_wait(&mutex);
cola[fin]=elemento;
fin=(fin + 1)% n;
c++;
cout<<"PRODUCER PRODUCED ITEM: "<<c<<endl;;
cout<<"ELEMENTO PRODUCIDO: "<<elemento<<endl;
sem_post(&mutex);//signal
sem_post(&ocupados);
}
}

void consumidor()
{
while(true){
sem_wait(&ocupados);
sem_wait(&mutex);
elemento = cola[frente];
frente=(frente + 1)% n;
sem_post(&mutex);//signal
sem_post(&libres);
cout<<"ELEMENTO CONSUMIDO: "<<elemento<<endl;
c++;
cout<<"CONSUMER CONSUMED ITEM: "<<c<<endl;

}
}

int main()
{
fin=n;
frente=0;
sem_init(&mutex,0,1);
sem_init(&ocupados,0,0);
sem_init(&libres,0,n);

thread Productor(productor);
thread Consumidor(consumidor);
Productor.join();
Consumidor.join();

return 0;
}

Você também pode gostar