Concurrent Programming (19530-V)

Dr. Richard S. Hall WS 01/02

- Übung 4 -

Assigned: 20.11.2001
Due: 27.11.2001

1. Exercise

a) What is the difference between a process and a thread?
b) What is interference with respect to threads and concurrent programming?
c) Describe a situation that causes interference and why it leads to incorrect program execution results.
d) How does mutual exclusion help with interference?
e) Given the following method, explain why any number of threads can be executing inside of it without causing interference:
    public int factorial(int n)
{
if (n < 0)
return -1;
else if (n == 0)
return 1;

int result = 1;
    for (i = 1; i <= n; i++)
{
int temp = result;
temp *= i;
result = temp;
}
return result;
}

2.  Exercise

Write a Java program that increments a shared integer 250 times using five threads named A, B, C, D and E. For each loop iteration, the threads should increment the shared integer by one, print the thread name and the value of the integer, and then sleep for 10 milliseconds. Look at the output of your program, is the result what you would expect? Describe and explain any non-deterministic behavior. What do the results of your program indicate about operations on primitive variable types in Java? (Refer to the javadoc page of the Thread class for naming, etc.)

3.  Exercise

Create a Java program where five threads share an input file and an output file. Each thread should read a single byte from the input file and then write that byte to the output file. Initially, do not worry about thread interference. Run the program multiple times on different files and check if the output file is identical to the input file (on Linux you can use the diff command to compare files). Modify the program to ensure that no thread interference can occur. For flexibility, implement your program so that you can specify the input file and the output file on the command line.