School of Computing and Information Systems SWEN90004 Modelling Complex Software Systems
Concurrency Workshop 1 solutions
The exercises
1. First, the class needs to extend Thread:
public class ConQuick extends Thread {
the constructor has to be renamed to ConQuick, and we need a run method:
public void run() {
quicksort();
}
The quicksort method has two recursive calls; we want to hand the first of these on to some other thread, let us call it lowSorter. We should also join the current thread to this new thread:
// create a new thread to sort the lower side
ConQuick lowSorter = new ConQuick(a, lo, pivot-1);
lowSorter.start();
try {
lowSorter.join()
}
catch (Exception e) {}
In fact we can easily get rid of the second recursive call. Turn the if into a while and replace
the second recursive call by something simpler:
// concentrate on sorting the higher half of the array
lo = pivot + 1;
Finally we need to update main, so that it starts an initial ConQuick thread:
//sort the array
ConQuick sort = new ConQuick(a, 0, a.length-1);
sort.start();
try {
sort.join();
}
catch (Exception e) {}
Timing results of course are machine dependent, and the core-to-thread ratio needs to be reasonably high to get proper benefit of parallelism¡ªwe also need to make up for the cost of creating and managing new threads.
2. The code for each of the attempts at a solution to the mutual exclusion problem is provided in the slides for lecture Con.02 (though remember that shared variables should be declared as volatile!)