linux-sysprog · beginner · ~15 min

Safe way to pass per-thread args

Recognise the shared-loop-variable thread-arg bug.

Challenge

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.

Task

Implement int arg_passing_safe(const char *how) that returns 1 if the strategy gives each thread its own argument storage, else 0.

Input

  • how: a strategy name string.

Output

1 for "heap" or "unique-stack-slot"; 0 for "shared-loop-variable".

Example

arg_passing_safe("heap")                  ->   1
arg_passing_safe("unique-stack-slot")     ->   1
arg_passing_safe("shared-loop-variable")  ->   0

Input format

how: an argument-passing strategy name.

Output format

1 for per-thread storage strategies, else 0.

Constraints

Safe: heap, unique-stack-slot. Unsafe: shared-loop-variable.

Starter code

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