linux-sysprog · advanced · ~15 min

Spawn and join N threads

Create several threads and collect their results with join.

Challenge

Spawn several threads, each carrying its own index, then join them and collect their results. pthread_join both waits for a thread and hands back its return value.

Task

Implement long sum_thread_ids(int n) that spawns n threads where thread i returns its index i, joins them all, and returns the sum of the returned indices.

Input

  • n: number of threads to spawn.

Output

The sum 0 + 1 + ... + (n-1) as a long.

Example

sum_thread_ids(4)   ->   6
sum_thread_ids(1)   ->   0
sum_thread_ids(5)   ->   10

Rules

  • Give each thread its own index (cast through intptr_t).
  • Join every thread and sum the returned values.

Input format

n: number of threads to spawn.

Output format

Sum of indices 0..n-1 as a long.

Constraints

Each thread returns its own index; join all before summing.

Starter code

#include <pthread.h>

long sum_thread_ids(int n) {
    /* TODO */
    return 0;
}

Common mistakes

Accessing shared state without acquiring mutex; deadlock due to out-of-order lock acquisition; forgetting pthread_join leading to resource leak.

Edge cases to handle

Zero iterations; single thread vs many concurrent threads; thread cancellation; lock contention under high load.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.