Prova teorica 2015.02.14
Jump to navigation
Jump to search
Testo: [1]
Esercizio c.1
Soluzione di Silas
#define MAX
monitor altcolbb{
queue buff;
color_t last_color; //0: red, 1:blue, -1:"superstate", means that both red and blue are accepted
int wait_red, wait_blue;
condition ok2read, redok, blueok;
void altcolbb(void){
buff = new queue();
last_color = -1;
wait_red = wait_blue = 0;
}
procedure entry void write(color_t color, generic_type val){
if(last_color == color || buff.length() == MAX){ //we can't enqueue if the colors are the same or if the buffer is full
if(color == 0){ //enqueue to "reds"
wait_red++;
redok.wait();
wait_red--;
}else{
wait_blue++;
blueok.wait();
wait_blue--;
}
}
buff.enqueue(val);
last_color = color;
ok2read.signal();
}
procedure entry generic_type read(void){
if(buff.length() == 0)
ok2read.wait();
generic_type ret = buff.dequeue();
if(buff.length() == 0)
last_color = -1;
switch(last_color){
case -1: {
if(wait_red>wait_blue)
redok.signal();
else
blueok.signal();
break;
}
case 0: {
redok.signal();
break;
}
case 1: {
blueok.signal();
break;
}
}
}
}