Exercises: Parallel Algorithms
These exercises review the three lessons of the chapter: concepts, the Fork/Join framework and performance. The parallel Fibonacci and Quicksort are explained in the Fork/Join lesson. Try each exercise before reading its solution: the solutions are grouped at the end of the page.
Concepts
9.1. Concurrent or parallel? Classify each situation as concurrent, parallel, both, or neither:
- (a) A web server on a single-core machine handles 100 connections by switching between them.
- (b) A Fork/Join sum runs on 8 cores.
- (c) A video player decodes the next frame while another thread plays the sound, on a 4-core laptop.
- (d) A program sorts an array with
Arrays.sorton anint[].
9.2. A lost update. Two threads each execute counter++ one million times on a shared int field. What values can counter have at the end? Explain why, and give two ways to fix it.
Fork/Join
9.3. Maximum in parallel. Write a RecursiveTask<Integer> that computes the maximum of an int[], following the structure of the sum example of the Fork/Join lesson.
9.4. Spot the mistake. A student writes the combination step of a Fork/Join task like this:
leftTask.fork();
double leftResult = leftTask.join();
rightTask.fork();
double rightResult = rightTask.join();
return leftResult + rightResult;
The result is correct, but the program is no faster than the sequential version. Why? How should it be written?
9.5. The threshold. A Fork/Join sum of elements is run with thresholds of 1, 1,000, 100,000 and elements. Predict qualitatively which thresholds give poor times, and why.
Performance
9.6. Amdahl. A program spends 80% of its time in a part that can be parallelized perfectly.
- (a) What is its maximum speedup with 4 processors? And with an unlimited number?
- (b) A measurement on 8 cores gives a speedup of 6. What parallel fraction does Amdahl's law deduce from it?
9.7. Reading measurements. A sequential program takes 12 s. Its parallel version takes 3.6 s on 4 cores and 2.4 s on 8 cores. Compute the speedup and the efficiency for each case. Using the Karp-Flatt metric, the experimentally determined serial fraction
decide whether the loss of efficiency is due to a fixed sequential part (constant ) or to an overhead that grows with the number of processors (growing ).
9.8. Work and span. Give the work and the span of: (a) the Fork/Join sum of elements; (b) Mergesort with its two recursive calls in parallel but a sequential merge. What is the maximum useful number of processors (work divided by span) for in case (b)?
9.9. Amdahl or Gustafson? With 4 processors and a sequential fraction of 20%, Amdahl's law predicts a speedup of 2.5, while Gustafson's law predicts 3.4. Explain why both can be right.
Solutions
9.1.
- (a) Concurrent, not parallel: several tasks progress in overlapping periods, but only one runs at any instant.
- (b) Parallel (and concurrent): the tasks run at the same instant on different cores.
- (c) Both: two independent activities progress at the same time, and with several cores they can truly run simultaneously.
- (d) Neither:
Arrays.sorton primitive arrays is sequential. (Arrays.parallelSortis the parallel version.)
9.2. Any value between 2 and 2,000,000 is possible in theory; in practice it is usually well below 2,000,000. counter++ is three steps: read the value, add one, write it back. If both threads read the same value before either writes, one increment is lost. On our machine, with the field declared volatile (so that every access really goes to memory), three runs gave 1,646,549, 1,761,926 and 1,578,876. Without volatile, the JIT compiler happened to optimize each loop into a single addition and the result was 2,000,000: the bug was still there, only hidden, which is what makes race conditions so dangerous. Fixes:
- use an
AtomicInteger(incrementAndGet()), or aLongAdderwhen contention is high; - better still, avoid sharing: each thread counts in a local variable and the results are added at the end, which is exactly what the Fork/Join pattern does with its return values.
(synchronized blocks also work, but they serialize the increments.)
9.3.
public class MaxTask extends RecursiveTask<Integer> {
private static final int THRESHOLD = 10_000;
private final int[] a;
private final int start, end;
public MaxTask(int[] a, int start, int end) {
this.a = a;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= THRESHOLD) { // small part: sequential
int max = Integer.MIN_VALUE;
for (int i = start; i < end; i++)
max = Math.max(max, a[i]);
return max;
}
int middle = start + (end - start) / 2;
MaxTask left = new MaxTask(a, start, middle);
MaxTask right = new MaxTask(a, middle, end);
left.fork(); // left half in another worker
int rightMax = right.compute(); // right half in this thread
int leftMax = left.join();
return Math.max(leftMax, rightMax);
}
}
It is invoked with ForkJoinPool.commonPool().invoke(new MaxTask(a, 0, a.length)). We checked it against Arrays.stream(a).max() on 5 million random numbers. The only changes from the sum are the neutral element (Integer.MIN_VALUE instead of 0) and the combination (Math.max instead of +): the same scheme works for any associative operation.
9.4. join waits for the task to finish. Calling leftTask.join() immediately after leftTask.fork() blocks until the left half is done, and only then starts the right half: the two halves run one after the other, plus the cost of creating tasks. The correct order starts the left half, computes the right half in the current thread while the left one runs elsewhere, and only then waits:
leftTask.fork();
double rightResult = rightTask.compute();
double leftResult = leftTask.join();
(invokeAll(leftTask, rightTask) followed by two join calls is an equivalent alternative.)
9.5.
- 1 element: about tasks, each doing a single addition. The cost of creating and scheduling them is far larger than the work: much slower than the sequential sum.
- 1,000 and 100,000: good values. There are enough tasks to keep all the cores busy and to balance the load, and each one does enough work to make its overhead negligible. The best value depends on the machine, which is why the lesson recommends measuring.
- : only two tasks. At most two cores are used, so on an 8-core machine the speedup cannot exceed 2.
9.6.
- (a) With and : . The limit is , however many processors are added.
- (b) From we get . About 95% of the program behaves as parallel, which limits the speedup to about 21.
9.7.
| Time | Speedup | Efficiency | Karp-Flatt | |
|---|---|---|---|---|
| 4 | 3.6 s | 3.33 | 83% | 0.067 |
| 8 | 2.4 s | 5.00 | 63% | 0.086 |
The serial fraction grows with (from 6.7% to 8.6%). If the only problem were a fixed sequential part, would stay constant. A growing points to an overhead that increases with the number of processors: more tasks to create, more synchronization, or contention for memory bandwidth. A larger threshold or less shared data are the usual remedies.
9.8.
- (a) Work (every element is added once, plus combinations) and span (the depth of the tree of additions). It parallelizes very well.
- (b) Work , as in sequential Mergesort. The span satisfies , because the two halves run in parallel but the merge of elements is sequential: , dominated by the last merge. The parallelism is : about for a million elements. Beyond some 20 processors there would be nothing useful to do. Parallelizing the merge as well (splitting it with binary search) reduces the span to and makes the algorithm truly scalable.
9.9. They answer different questions. Amdahl keeps the problem size fixed and asks how much faster it gets: with and , . Gustafson keeps the time fixed and lets the problem grow with the processors, so that the parallel part grows and the sequential part stays the same: . If more cores are used to solve the same problem faster, Amdahl's estimate applies; if they are used to solve bigger problems in the same time (finer simulations, larger datasets), Gustafson's does.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.