linux-sysprog · advanced · ~15 min

Return a value from a thread

Collect a thread's result via join's value pointer.

Challenge

A thread function returns a void*; pthread_join's second argument captures it. Carrying a small integer through that pointer (cast via intptr_t) is a common LP64-safe idiom.

Task

Implement long square_in_thread(long v) that runs a thread returning v*v through its return value, retrieves it with pthread_join, and returns it.

Input

  • v: the value to square.

Output

v * v.

Example

square_in_thread(5)    ->   25
square_in_thread(0)    ->   0
square_in_thread(12)   ->   144

Rules

  • Return (void*)(intptr_t)(v*v) from the thread.
  • Capture it with pthread_join's second argument.

Input format

v: the value to square.

Output format

v * v.

Constraints

Return the result via the thread return value; capture it with join.

Starter code

#include <pthread.h>

long square_in_thread(long v) {
    /* TODO */
    return 0;
}

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