So in this code, like in the title said, we are showing how our locks and c. v. work. It's a basic consumer-producer program(with 2 consumers) where each consumer will "consume" 3 units if available, if not then he will go to sleep, until the producer finishes producing 'i' quantity units. The units are represented with a counter, and can be modified to try different results, in this examples, the consumer consumes 3, and the producer produces 4.
#include "example.h"
using namespace std;
Thread *t;
Lock *l;
Condition *c;
int avail = 0;
int p, i=0;
static void consumer(int n) {
for(int j = 0; j< 3; j++){
l->Acquire();
if (avail == 0) {
cout <<"Consumer "<< n << " Sleeping" << endl;
c->Wait(l);
}
cout <<"Consumer "<< n << " Consuming something - Total :" << avail << endl;
avail--;
l->Release();
i--;
}
}
static void producer(int n) {
while (i!=4) {
l->Acquire();
avail++;
cout <<"Producer " << n << " Producing something - Total :" << avail << endl;
c->Signal(l);
l->Release();
i++;
}
}
Example::Example() {
l = new Lock("l");
c = new Condition("c",l);
t = new Thread("consumer");
t->Fork((VoidFunctionPtr)consumer, (void *)1);
t = new Thread("consumer");
t->Fork((VoidFunctionPtr)consumer, (void *)2);
t = new Thread("producer");
t->Fork((VoidFunctionPtr)producer, (void *)1);
}
Screen Capture:
Ya que implementaste condition variables, hubiese sido bueno ver una implementacion de productor-consumidor pero con mas de uno de cada tipo, asi se podria observar si el hecho de que uno se duerme no bloquea a los demas (que los condition variables funcionen como deben).
ResponderEliminarGracias por la sugerencia!. El nuevo código contiene dos consumers y un producer( no vi necesidad de dos producers), los consumers duermen cuando no haya unidades, y mientras duermen dejan al producer crear lo que debe sin interferir. Gracias a eso en verdad pude ver que funcionan las c. v.
ResponderEliminarSaludos!