CS 334: HW 10

Instructions

This homework has two types of problems:

  • Self Check: You are strongly encouraged to think about and work through these questions, but you will not submit answers to them.

  • Problems: You will turn in answers to these questions.

Reading

Problems

1. Race Conditions and Atomicity

The DoubleCounter class defined below has methods incrementBoth and getDifference. Assume that DoubleCounter will be used in multi-threaded applications.

class DoubleCounter { 
  protected int x = 0;
  protected int y = 0; 

  public int getDifference() { 
    return x - y; 
  } 

  public void incrementBoth() { 
    x++; 
    y++; 
  } 
} 

There is a potential data race between incrementBoth and getDifference if getDifference is called between the increment of x and the increment of y. You may assume that x++ and y++ execute atomically (although this is not always guaranteed...).

  1. What are the possible return values of getDifference if there are two threads that each invoke incrementBoth exactly once at the same times as a third thread invokes getDifference?

  2. What are the possible return values of getDifference if there are n threads that each invoke incrementBoth exactly once?

  3. Data races can be prevented by inserting synchronization primitives. One option is to declare

    public synchronized int getDifference() {...} 
    public int incrementBoth() {...}
    

    This will prevent two threads from executing method getDifference at the same time. Is this enough to ensure that getDifference always returns 0? Explain briefly.

  4. Is the following declaration

    public int getDifference() {...} 
    public synchronized int incrementBoth() {...}
    

    sufficient to ensure that getDifference always returns 0? Explain briefly.

  5. What are the possible values of getDifference if the following declarations are used?

    public synchronized int getDifference() {...} 
    public synchronized int incrementBoth() {...}
    

Submitting Your Work

Submit your answers to the GradeScope assignment named, for example, "HW 0". It should:

  • be clearly written or typed,
  • include your name and HW number at the top,
  • list any students with whom you discussed the problems, and
  • be a single PDF file, with one problem per page.

You will be asked to resubmit homework not satisfying these requirements. Please select the pages for each question when you submit.