Midterm 2 Solutions
NAME: STUDENT ID:
General Instructions: • Write your name and student ID clearly above. • You have 1 hour and 15 minutes to write the exam. No extra time will be given. • There are 4 questions in the exam, all with subparts. The questions combine for a maximum of 100 points. • You must write your answers clearly in the space provided for each question. You might use the backside of each page, as well as any additional sheets as required. If you are using additional space, you must clearly label the question no. that you are answering. Any loose sheets must have your name and student ID written clearly. • The exam is open book/open notes, however, …show more content…
foo(9) bar(9) Ans: Here, the semaphores are used to synchronize the order of execution of different threads. We have seen examples in the class and in the textbook of how to order the execution of two threads using semaphores. Here, we will extend that to 10 threads. Have a global array of semaphores: semaphore sem[10]; Initialize sem[0]=1, sem[1]=sem[2]=...=sem[9]=0; Code for thread i: wait(sem[i]); foo(i); bar(i); signal(sem[(i+1)%10]); Note: You can have code where thread 0 does not have the wait statement, or/and thread 9 does not have the signal statement. Also, I’ll give credit if you have signal(sem[i+1]) instead of signal(sem[(i+1)%10]. I’ll also accept answers where you don’t have an array but have shown different semaphores for each thread and explained how it will work. (d) (24 pts) Starting with thread 0, have thread i execute foo before thread i + 1 executes foo. Once all threads have executed foo, reverse the order of execution for bar, i.e., have thread i execute bar before thread i − 1, starting with thread 9. In other words, the desired order of execution should be: foo(0) foo(1) ... foo(9) bar(9) bar(8) ... bar(0)
Ans: The solution here is