linux-sysprog · intermediate · ~10 min

Pass an integer to each thread (by value)

Cast value through intptr_t to avoid the &loop-variable trap.

Challenge

Implement int sum_thread_ids(int n) that:

  1. Spawns n threads.
  2. Passes each thread its own index i (0..n-1) — by value, not by address.
  3. Each thread returns its id back through void *.
  4. Main joins all threads and returns the sum of returned ids.

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.

Why this matters

The number-one pthread bug: passing &i from a loop. Practice the safe alternative.

Starter code

#include <pthread.h>
#include <stdint.h>
int sum_thread_ids(int n) {
    /* TODO */
    return -1;
}

Background lessons

Up next

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