linux-sysprog · advanced · ~15 min

Parallel array sum

Split work across pthreads and combine with join.

Challenge

Sum an array in parallel: split it in half, let two POSIX threads add their halves, then combine the partial sums.

Task

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.

Input

  • a: array of n ints.
  • n: element count (may be 0).

Output

The sum of all n elements as a long.

Example

parallel_sum([1,2,3,4,5,6], 6)   ->   21
parallel_sum([7], 1)             ->   7
parallel_sum(a, 0)               ->   0

Edge cases

  • n == 0: return 0.
  • Odd n: the split need not be exactly even.

Rules

  • Use two threads and join both before reading their partial sums.

Input format

a: array of n ints; n: element count (>= 0).

Output format

Sum of all elements as a long.

Constraints

Use two threads; join both before combining results.

Starter code

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