Difference between revisions of "Prova teorica 2015.02.14"
Jump to navigation
Jump to search
(Created page with "Testo: [http://www.cs.unibo.it/~renzo/so/compiti/2015.02.14.tot.pdf] == Esercizio c.1 == ===Soluzione di Silas=== <syntaxhighlight lang="C"> #define MAX monitor altcolbb{ ...") |
|||
Line 24: | Line 24: | ||
redok.wait(); | redok.wait(); | ||
wait_red--; | wait_red--; | ||
− | }else{ | + | }else{ //enqueue to "blues" |
wait_blue++; | wait_blue++; | ||
blueok.wait(); | blueok.wait(); | ||
Line 30: | Line 30: | ||
} | } | ||
} | } | ||
− | buff.enqueue(val); | + | buff.enqueue(val); //append val and update last_color |
last_color = color; | last_color = color; | ||
ok2read.signal(); | ok2read.signal(); | ||
Line 40: | Line 40: | ||
generic_type ret = buff.dequeue(); | generic_type ret = buff.dequeue(); | ||
if(buff.length() == 0) | if(buff.length() == 0) | ||
− | last_color = -1; | + | last_color = -1; //if buff is empty both colors can now be added |
switch(last_color){ | switch(last_color){ | ||
case -1: { | case -1: { | ||
− | if(wait_red>wait_blue) | + | if(wait_red>wait_blue) //if there are more "reds" waiting to write we signal them |
redok.signal(); | redok.signal(); | ||
else | else | ||
− | blueok.signal(); | + | blueok.signal(); //otherwise we signal "blues" |
break; | break; | ||
} | } | ||
case 0: { | case 0: { | ||
− | + | blueok.signal(); | |
break; | break; | ||
} | } | ||
case 1: { | case 1: { | ||
− | + | redok.signal(); | |
break; | break; | ||
} | } |
Revision as of 16:16, 26 May 2017
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{ //enqueue to "blues"
wait_blue++;
blueok.wait();
wait_blue--;
}
}
buff.enqueue(val); //append val and update last_color
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; //if buff is empty both colors can now be added
switch(last_color){
case -1: {
if(wait_red>wait_blue) //if there are more "reds" waiting to write we signal them
redok.signal();
else
blueok.signal(); //otherwise we signal "blues"
break;
}
case 0: {
blueok.signal();
break;
}
case 1: {
redok.signal();
break;
}
}
}
}