linux-sysprog · beginner · ~15 min
Recognise the shared-loop-variable thread-arg bug.
Passing &i from a spawn loop is the classic thread-arg bug: every thread ends up seeing the final loop value because they share one variable. Give each thread its own copy instead. Classify an argument-passing strategy.
Implement int arg_passing_safe(const char *how) that returns 1 if the strategy gives each thread its own argument storage, else 0.
how: a strategy name string.1 for "heap" or "unique-stack-slot"; 0 for "shared-loop-variable".
arg_passing_safe("heap") -> 1
arg_passing_safe("unique-stack-slot") -> 1
arg_passing_safe("shared-loop-variable") -> 0
how: an argument-passing strategy name.
1 for per-thread storage strategies, else 0.
Safe: heap, unique-stack-slot. Unsafe: shared-loop-variable.
#include <string.h>
int arg_passing_safe(const char *how) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.