linux-sysprog · beginner · ~10 min

Create one thread that returns a value

pthread_create → pthread_join → cast return value.

Challenge

Run the smallest possible pthread program: spawn one thread, wait for it, and read back the value it returned.

Task

Implement int run_one_thread(void) that spawns a thread, joins it, and returns the thread's result.

Input

No parameters.

Output

Creates one thread whose worker returns (void *)(intptr_t)42, joins it with pthread_join, and returns that value cast back to int (so 42). Returns -1 if pthread_create or pthread_join fails.

Example

run_one_thread()   ->   42

Edge cases

  • Any thread-create or join failure returns -1.

Why this matters

The smallest possible pthread program — spawn one thread, join it, read its return value.

Input format

No parameters.

Output format

The value the thread returned (42), or -1 if create/join fails.

Constraints

Worker returns (void*)(intptr_t)42; main joins and casts the result back to int.

Starter code

#include <pthread.h>
#include <stdint.h>
int run_one_thread(void) {
    /* TODO */
    return -1;
}

Background lessons

Up next

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