COMP1521 18s1 COMP1521 18s1 Final Exam Comp Sys Fundamentals
[Instructions] [Documentation]
[Q1] [Q2] [Q3] [Q4] [Q5] [Q6] [Q7] [Q8] [Q9] [Q10]

Question 9 (4 marks)

Consider the following pseudo-C solution to the readers/writers problem, where multiple processes are accessing a shared resource:

// shared global variables
int   nreaders;  // initial value 0
sem_t *mx, *w;   // both initially 1

void reader(void) {
   while (1) {
      wait(mx);
      nreaders++;
      if (nreaders == 1) wait(w);
      signal(mx);
      // ... do some reading ...
      wait(mx);
      nreaders--;
      if (nreaders == 0) signal(w);
      signal(mx);
   }
}

void writer(void) {
   while (1) {
      wait(w);
      // ... do some writing ...
      signal(w);
   }
}

Note that this code uses the conventional names wait() and signal() instead of C's names sem_wait() and sem_post().

  1. Explain in at most one or two short, clear sentences:

    1. What is the purpose of the mx semaphore?

    2. What is the purpose of the w semaphore?

  2. Using C's semaphore functions, write complete C function calls for each of the following:

    1. Initialising the mx semaphore to 1

    2. signal(w);

    Hint: look up the man entries for sem_init and sem_post, and assume that the pshared parameter has the value 0. Also, assume that the two sem_t objects were already created using the sem_open function, and mx and w point to them.

  3. This solution correctly enforces the mutual exclusion rules on the shared resource (no more than 1 writer, no writers if any readers). However, it does not prevent starvation. Briefly, describe the circumstances under which this might occur.

Type your answers to this question into the appropriate place in the q9.txt file, and submit it using the command:

submit q9

This will make a copy of the q9.txt file as your answer for this question. You can run the submit command as many times as you like, but only the most recent submission will be marked.