linux-sysprog · advanced · ~15 min
Collect a thread's result via join's value pointer.
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.
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.
v: the value to square.v * v.
square_in_thread(5) -> 25
square_in_thread(0) -> 0
square_in_thread(12) -> 144
(void*)(intptr_t)(v*v) from the thread.pthread_join's second argument.v: the value to square.
v * v.
Return the result via the thread return value; capture it with join.
#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.