linux-sysprog · intermediate · ~10 min
Cast value through intptr_t to avoid the &loop-variable trap.
Implement int sum_thread_ids(int n) that:
n threads.i (0..n-1) — by value, not by address.void *.For n = 4, the expected sum is 0+1+2+3 = 6. The bug to avoid: passing &i from the loop makes every thread read the post-loop value of i and the sum becomes wrong.
The number-one pthread bug: passing &i from a loop. Practice the safe alternative.
#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.