Skip to main content

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.sort on an int[].

Solution to 9.1

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.

Solution to 9.2

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.

Solution to 9.3

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?

Solution to 9.4

9.5. The threshold. A Fork/Join sum of 10810^8 elements is run with thresholds of 1, 1,000, 100,000 and 5×1075 \times 10^7 elements. Predict qualitatively which thresholds give poor times, and why.

Solution to 9.5

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?

Solution to 9.6

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

e=1/S−1/p1−1/pe = \frac{1/S - 1/p}{1 - 1/p}

decide whether the loss of efficiency is due to a fixed sequential part (constant ee) or to an overhead that grows with the number of processors (growing ee).

Solution to 9.7

9.8. Work and span. Give the work and the span of: (a) the Fork/Join sum of nn 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 n=220n = 2^{20} in case (b)?

Solution to 9.8

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.

Solution to 9.9


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.sort on primitive arrays is sequential. (Arrays.parallelSort is the parallel version.)

Back to exercise 9.1

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 a LongAdder when 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.)

Back to exercise 9.2

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.

Back to exercise 9.3

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.)

Back to exercise 9.4

9.5.

  • 1 element: about 2×1082 \times 10^8 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.
  • 5×1075 \times 10^7: only two tasks. At most two cores are used, so on an 8-core machine the speedup cannot exceed 2.

Back to exercise 9.5

9.6.

  • (a) With f=0.8f = 0.8 and p=4p = 4: S=10.2+0.8/4=10.4=2.5S = \dfrac{1}{0.2 + 0.8/4} = \dfrac{1}{0.4} = 2.5. The limit is 11−0.8=5\dfrac{1}{1 - 0.8} = 5, however many processors are added.
  • (b) From 16=(1−f)+f8\dfrac{1}{6} = (1 - f) + \dfrac{f}{8} we get f=(1−16)⋅87≈0.952f = \left(1 - \dfrac{1}{6}\right) \cdot \dfrac{8}{7} \approx 0.952. About 95% of the program behaves as parallel, which limits the speedup to about 21.

Back to exercise 9.6

9.7.

ppTimeSpeedup SSEfficiency S/pS/pKarp-Flatt ee
43.6 s3.3383%0.067
82.4 s5.0063%0.086

The serial fraction ee grows with pp (from 6.7% to 8.6%). If the only problem were a fixed sequential part, ee would stay constant. A growing ee 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.

Back to exercise 9.7

9.8.

  • (a) Work O(n)O(n) (every element is added once, plus O(n/threshold)O(n / \text{threshold}) combinations) and span O(log⁡n)O(\log n) (the depth of the tree of additions). It parallelizes very well.
  • (b) Work O(nlog⁡n)O(n \log n), as in sequential Mergesort. The span satisfies S(n)=S(n/2)+O(n)S(n) = S(n/2) + O(n), because the two halves run in parallel but the merge of nn elements is sequential: S(n)∈O(n)S(n) \in O(n), dominated by the last merge. The parallelism is W/S=O(log⁡n)W / S = O(\log n): about log⁡2220=20\log_2 2^{20} = 20 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 O(log⁡3n)O(\log^3 n) and makes the algorithm truly scalable.

Back to exercise 9.8

9.9. They answer different questions. Amdahl keeps the problem size fixed and asks how much faster it gets: with 1−f=0.21 - f = 0.2 and p=4p = 4, S=1/(0.2+0.8/4)=2.5S = 1 / (0.2 + 0.8/4) = 2.5. 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: S=p−(1−f)(p−1)=4−0.2⋅3=3.4S = p - (1 - f)(p - 1) = 4 - 0.2 \cdot 3 = 3.4. 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.

Back to exercise 9.9

Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.