#define N 100 /* number of slots in buffer */ semaphore mutex = 1; semaphore A = N; semaphore B = 0; void producer(void) { int item; while (TRUE) { produce_item(item); P(A); P(mutex); enter_item(item); /* put item into the shared buffer */ V(mutex); V(B); } }
void consumer(void) { int item; while (TRUE) { P(B); P(mutex); remove_item(item); /* get item from the shared buffer */ V(mutex); V(A); comsume_item(item); } }
P0 | has | 1 | of R2 | and wants | 1 | of R3 |
P1 | has | 2 | of R0 | |||
has | 1 | of R1 | ||||
P2 | has | 1 | of R4 | and wants | 1 | of R4 |
has | 2 | of R5 | ||||
P3 | has | 2 | of R3 | and wants | 1 | of R2 |
P4 | has | 1 | of R4 | and wants | 2 | of R5 |
Show how you would modify this program (if at all) to ensure that the ratings and number of responses are correctly calculated given the fact that multiple threads are involved. You may use either monitors or semaphores to construct your solution.
import java.util.Scanner; import java.io.File; public class MovieRating { public static void main(String [] args) throws Exception { Scanner kb= new Scanner(System.in); int i,j,whichOne,totalResponses; int numThreads= 10; Thread [] rateit= new Thread[numThreads]; Movie m[]= new Movie[4]; m[0]= new Movie("Gone with the Wind"); m[1]= new Movie("Ice Age"); m[2]= new Movie("SAW MLVXII"); m[3]= new Movie("The Princess Bride"); // each thread obtains 100 responses ... for (i=0; i<100; i++) { for (j=0; j<numThreads; j++) { whichOne= (int) (Math.random()*4.0); rateit[j]= new Thread(new RateThread(m[whichOne])); } for (j=0; j<numThreads; j++) rateit[j].start(); for (j=0; j<numThreads; j++) rateit[j].join(); } totalResponses= 0; System.out.printf("%-20s %5s %5s\n","Movie","Score","Responses"); System.out.println("------------------------------------------------------"); for (i=0; i<4; i++) { System.out.printf("%-20s %5d %5d\n",m[i].name,m[i].score,m[i].numResponses); totalResponses+= m[i].numResponses; } System.out.println("------------------------------------------------------"); System.out.printf("%-20s %5s %5d\n","Total Responses","",totalResponses); } } class RateThread implements Runnable { private Movie m; public RateThread(Movie m) { this.m= m; } public void run() { int response= getResponse(); m.score+= response; m.numResponses++; } // find out from survey-taker how many thumbs-ups they give it // 1= thumbs up; 0=thumb up, thumb down; -1= thumbs down public int getResponse() { System.out.println("What did you think of the movie "+m.name); return (int) (Math.random()*3.0) - 1; } } class Movie { public Movie(String name) { this.name= name; score= 0; numResponses= 0; } public int score,numResponses; public String name; }