CSE 306 -- Operating Systems

Spring 2002

Solution to the Midterm Exam


1. [30 points]

The following function is proposed for use in a multi-threaded program.

    int alpha = 0;

    int beta(void)
    {
      int gamma = alpha;
      alpha++;
      return gamma;
    }

(a) [10] Explain why two calls to beta() in separate threads could return the
    same result.  (Show the sequence of instructions executed by beta() in each
    thread, and how the two sequences could be interleaved.)

	1. load old alpha (gamma)
	2. copy to register
	3. increment register
	4. store new alpha
	5. return gamma

	instruction sequence:
	P0  1           2 3 4 5
	P1    1 2 3 4 5
	same alpha loaded (this is the important part), same alpha stored, same
	gamma returned.

(b) [10] What hardware support would be helpful to guarantee that beta()
    returns a different value each time it is called, even if called
    simultaneously in separate threads on separate processors?  (you can ignore
    arithmetic overflow) 

	This is like a "test and increment" operation, similar to the "test and
	set" operation.  It could be a single instruction.
	Force the memory to do serialization (but this is not really enough).
	Implement this as an atomic update instruction.

(c) [10] Using a semaphore, rewrite the function so every call to beta()
    (whether in one thread or in many) will return a different result from the
    sequence 0,1,2,3,..., without omitting any element of the sequence.

	Required elements:
	  declare a semaphore (global)
	  initialize it (outside beta)
	  wait() (before loading alpha, inside beta)
	  signal() (after storing alpha, inside beta)
	Perhaps state explicitly that alpha is the critical resource, and that
	(load alpha, increment, store alpha) is the critical section.


2. [30 points]
   Copy a data page only after it has been written, i.e. modified.
   

3. [30 points - 5 points each part]

  a) Reduces to FCFS
  b) Too much context switching due to too short Q
  c)  "   "      "        "      "   "  "    "   "
  d) Since T >> S this still leaves open possibility of Q too short
  e) Ideal since satisfies I/O-bound processes in one quantum
  f) Again, Q potentially too big, thus reducing to FCFS


4. [10 points}
   ThreadCB cthread = MMU.getPTBR().getTask().getCurrentThread()