linux-sysprog · advanced · ~15 min
Create several threads and collect their results with join.
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.
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.
n: number of threads to spawn.The sum 0 + 1 + ... + (n-1) as a long.
sum_thread_ids(4) -> 6
sum_thread_ids(1) -> 0
sum_thread_ids(5) -> 10
intptr_t).n: number of threads to spawn.
Sum of indices 0..n-1 as a long.
Each thread returns its own index; join all before summing.
#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.