Linux System Programming · intermediate · ~10 min
Return values from a thread back to its joiner.
Threads return void *. The joiner passes void ** to pthread_join and gets the pointer back. The pointer must remain valid after the thread exits:
(void *)(intptr_t)42) — safe for ints up to pointer width.malloc'd struct — joiner is responsible for freeing.#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct { int sum; int count; } result_t;
static void *worker(void *arg) {
int n = (int)(intptr_t)arg;
result_t *r = malloc(sizeof *r);
r->sum = n * (n + 1) / 2;
r->count = n;
return r;
}
int main(void) {
pthread_t t;
pthread_create(&t, NULL, worker, (void *)(intptr_t)10);
void *raw;
pthread_join(t, &raw);
result_t *r = raw;
printf("sum=%d count=%d\n", r->sum, r->count);
free(r);
return 0;
}
Threads return void *. Safe options: a value-cast int, a global, or a malloc'd buffer the joiner frees. Never a stack-local address.