linux-sysprog · intermediate · ~10 min
Cast value through intptr_t to avoid the &loop-variable trap.
Give each thread its own index by value (not by a shared pointer), have each thread return that index, and sum the results — the safe pattern that avoids the classic &loop_variable race.
Implement int sum_thread_ids(int n) that spawns n threads, gives thread i the value i, and returns the sum of the values the threads report back.
n: how many threads to spawn (indices 0 .. n-1).Each thread is passed its index by value (cast through intptr_t, not via &i), returns that index through its void * result, and the function returns the sum of all returned indices: 0 + 1 + ... + (n-1).
sum_thread_ids(1) -> 0
sum_thread_ids(4) -> 6 (0+1+2+3)
sum_thread_ids(10) -> 45
sum_thread_ids(1) returns 0.&i from the loop is the bug to avoid — every thread would read the final value of i.intptr_t), never by address of the loop variable.The number-one pthread bug: passing &i from a loop. Practice the safe alternative.
n: the number of threads (indices 0..n-1).
The sum 0+1+...+(n-1) of the indices the threads return.
Pass each index by value through intptr_t (never &i). Each thread returns its index via void*.
#include <pthread.h>
#include <stdint.h>
int sum_thread_ids(int n) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.