02158  Concurrent Programming - Mini Lab 3: Critical Region with Semaphores
Technical University of Denmark DTU
02158 Concurrent Programming        Fall 2024
Mini Lab 3: Critical Region with Semaphores
Home Plan Material  

Purpose

To use semaphores to protect shared variables.

Prerequisites

Read about semaphores in [Andrews], chapter 4.

Instructions

The synchronization problem from Mini Lab 2 is now to be solved using semaphores.

  1. Fetch the program Counting.java from CP Mini Lab 2.
  2. Compile and run the program a couple of times to see the race-condition effect.

  3. Fetch Semaphore.java. This is the Java code for a class of general semaphores with the usual operations:

      Semaphore(int s0)       // Constructor (sets the initial value, s0>=0)
      void P() 
      void V()
    
    

    [The Semaphore class should be use as is. The operation P() may throw an InterruptedException. This should just be caught and ignored. ]

  4. Use an instance of the Semaphore class to make a critical region around x++, such that the increment becomes atomic.

    Run the program again and find:

  5. When you have learned about Java monitors, you may study the source code further.

Enjoy!

Hans Henrik Løvengreen, Oct 2, 2024