linux-sysprog · advanced · ~15 min
Split work across pthreads and combine with join.
Sum an array in parallel: split it in half, let two POSIX threads add their halves, then combine the partial sums.
Implement long parallel_sum(const int *a, int n) that sums a[0..n-1] using two threads (each summing one half), joins both, and returns the total.
a: array of n ints.n: element count (may be 0).The sum of all n elements as a long.
parallel_sum([1,2,3,4,5,6], 6) -> 21
parallel_sum([7], 1) -> 7
parallel_sum(a, 0) -> 0
n == 0: return 0.n: the split need not be exactly even.a: array of n ints; n: element count (>= 0).
Sum of all elements as a long.
Use two threads; join both before combining results.
#include <pthread.h>
long parallel_sum(const int *a, int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.