Linux System Programming · intermediate · ~10 min
Return a value from a thread back to the thread that joins it.
A thread function returns a void * (a generic pointer that can point to any type). The thread that calls pthread_join passes a void ** to receive that pointer back.
The key rule: the returned pointer must stay valid after the thread exits. When a thread ends, its stack is destroyed. Any pointer into that stack becomes invalid.
(void *)(intptr_t)42). This is safe for integers that fit in a pointer. intptr_t is an integer type guaranteed to hold a pointer value.malloc'd struct. The pointer stays valid after the thread exits. The joiner is then responsible for calling free.#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;
}
free a malloc'd return value on the joiner side. This causes a memory leak.void *; the joiner receives it through a void ** passed to pthread_join.malloc'd buffer the joiner frees.