linux-sysprog · advanced · ~15 min

Double a value in a thread

Pass an argument into a thread safely.

Challenge

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.

Task

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.

Input

  • v: the value to double.

Output

v * 2.

Example

double_in_thread(21)   ->   42
double_in_thread(0)    ->   0
double_in_thread(-5)   ->   -10

Rules

  • Pass a pointer to a local; have the thread do *p *= 2.
  • Join before reading the result.

Input format

v: the value to double.

Output format

v * 2.

Constraints

Pass by pointer; join before reading the result.

Starter code

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