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;
}

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