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

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.

Task

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.

Input

  • n: how many threads to spawn (indices 0 .. n-1).

Output

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).

Example

sum_thread_ids(1)    ->   0
sum_thread_ids(4)    ->   6     (0+1+2+3)
sum_thread_ids(10)   ->   45

Edge cases

  • sum_thread_ids(1) returns 0.
  • Passing &i from the loop is the bug to avoid — every thread would read the final value of i.

Rules

  • Pass each index by value (via intptr_t), never by address of the loop variable.

Why this matters

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

Input format

n: the number of threads (indices 0..n-1).

Output format

The sum 0+1+...+(n-1) of the indices the threads return.

Constraints

Pass each index by value through intptr_t (never &i). Each thread returns its index via void*.

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.