linux-sysprog · advanced · ~15 min

Spawn and join N threads

Create several threads and collect their results with join.

Challenge

Implement long sum_thread_ids(int n) that spawns n threads, each returning its own index (0..n-1) via the thread return value, joins them, and returns the sum of the indices.

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.