linux-sysprog · advanced · ~15 min
Pass an argument into a thread safely.
Pass a value into a worker thread by pointer, let the thread modify it, then read the result back after joining. Joining before the local goes out of scope is what makes sharing a stack variable safe.
Implement long double_in_thread(long v) that starts one thread, passes v to it by pointer, has the thread double it, joins, and returns the doubled value.
v: the value to double.v * 2.
double_in_thread(21) -> 42
double_in_thread(0) -> 0
double_in_thread(-5) -> -10
*p *= 2.v: the value to double.
v * 2.
Pass by pointer; join before reading the result.
#include <pthread.h>
long double_in_thread(long v) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.