Prova teorica 2015.02.14

From Sistemi Operativi
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{ //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;
			}
		}
	}
	
}