Pass Arguments to and Return Values from pthreads
Pass arguments to a pthread through void pointers and get results back with pthread_join, a result struct or pthread_exit, without dangling pointers.

A pthread start routine has exactly one parameter, a void *, and exactly one return value, also a void *. Everything real programs want to send into a thread, several numbers, a buffer and a mode flag, and everything they want back, a count and an error code, has to squeeze through those two pointers. Doing it badly is the source of most beginner thread bugs: arguments that change under the thread's feet, results that point into a dead stack frame, and integers smuggled through casts that work on one platform and warn on another. This post lays out the safe patterns for Linux with glibc 2.41 and GCC 15, after the basics in creating and joining threads.
The shape of the interface
void *worker(void *arg);
int pthread_create(pthread_t *t, const pthread_attr_t *attr,
void *(*start)(void *), void *arg);
int pthread_join(pthread_t t, void **retval);arg goes in at pthread_create and arrives as the parameter. Whatever the function returns, or passes to pthread_exit, comes out at pthread_join through retval. Both are raw addresses, so the compiler cannot check that you cast them back to the right type. The contract between the creator and the worker is a convention you hold in your head, so keep it narrow and obvious.
Pattern 1: a struct that carries inputs and outputs
The cleanest pattern is one struct per thread that holds the inputs the worker reads and the outputs it writes. The creator owns the struct, the worker gets a pointer, and the join is the synchronization point:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct range_job {
const int *data; /* input: shared, read-only */
size_t begin; /* input */
size_t end; /* input */
long sum; /* output */
};
static void *sum_range(void *arg)
{
struct range_job *job = arg;
long total = 0;
for (size_t i = job->begin; i < job->end; i++)
total += job->data[i];
job->sum = total;
return NULL;
}
int main(void)
{
int numbers[8] = {1, 2, 3, 4, 5, 6, 7, 8};
pthread_t threads[2];
struct range_job jobs[2] = {
{ numbers, 0, 4, 0 },
{ numbers, 4, 8, 0 },
};
for (int i = 0; i < 2; i++) {
int rc = pthread_create(&threads[i], NULL, sum_range, &jobs[i]);
if (rc != 0) {
fprintf(stderr, "pthread_create: %s\n", strerror(rc));
return EXIT_FAILURE;
}
}
long grand_total = 0;
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
grand_total += jobs[i].sum;
}
printf("total = %ld\n", grand_total);
return 0;
}total = 36The input array is shared but only read, so no synchronization is needed. Each thread writes to its own sum field, and the creator reads those fields only after the matching join. The join guarantees the write is visible. The return value of the thread is unused here (NULL), because the struct carries the result.
Why prefer this over the return value? It scales. Adding a field to the struct changes no function signature, the types are checked at the one place the pointer is cast, and the memory lives in the creator's frame, so there is nothing to free.
Pattern 2: the loop variable trap
Using the same address for every thread is the most common bug:
for (int i = 0; i < 4; i++)
pthread_create(&threads[i], NULL, worker, &i); /* wrong */All four threads receive the address of the same i. By the time a thread dereferences it, the loop may have advanced, or ended and the variable gone out of scope. The output of a program that prints *(int *)arg is unpredictable: it may print 4 four times or any mix. Give each thread its own storage, either an array int ids[4] indexed by i, or a struct per thread as above.
Pattern 3: passing a small integer by value
POSIX does not promise that an integer fits in a pointer, but C provides intptr_t and uintptr_t for that, and a conversion through them is well-defined for values that fit:
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
static void *worker(void *arg)
{
int id = (int)(intptr_t)arg;
return (void *)(intptr_t)(id * 10);
}
int main(void)
{
pthread_t t;
void *ret;
pthread_create(&t, NULL, worker, (void *)(intptr_t)7);
pthread_join(t, &ret);
printf("worker returned %d\n", (int)(intptr_t)ret);
return 0;
}worker returned 70The double cast through intptr_t avoids the "cast to pointer from integer of different size" warning that a bare (void *)id triggers on 64-bit targets. Use this only for small, always-valid integers. The return value NULL is also a pointer value, so a thread that returns the integer 0 this way is indistinguishable from a thread that returned nothing. For anything where the distinction matters, use a struct. Note that PTHREAD_CANCELED, the value pthread_join yields for a cancelled thread, is also a pointer (on glibc it is (void *) -1), so an integer return of -1 collides with it.
Pattern 4: heap-allocated results
When the thread allocates its result, the join hands the pointer back to a creator that then owns it:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void *make_greeting(void *arg)
{
const char *name = arg;
size_t len = strlen(name) + 8;
char *text = malloc(len);
if (text == NULL)
return NULL;
snprintf(text, len, "hello, %s", name);
return text;
}
int main(void)
{
pthread_t t;
void *result = NULL;
pthread_create(&t, NULL, make_greeting, "Ada");
pthread_join(t, &result);
if (result != NULL) {
printf("%s\n", (char *)result);
free(result);
}
return 0;
}hello, AdaNote the lifetime of "Ada": a string literal has static storage duration, so the pointer stays valid for the whole run. The returned buffer comes from malloc, which is thread-safe in glibc, and the creator frees it. This is the pattern to use when the result size is not known until the thread has run.
Never return the address of a local variable:
static void *broken(void *arg)
{
int answer = 42;
return &answer; /* wrong: the stack is gone after the thread exits */
}GCC warns with -Wreturn-local-addr (part of -Wall): "function returns address of local variable". Heed it. Reading the returned pointer after the join dereferences freed stack memory.
Using pthread_exit
A thread can also end through pthread_exit(void *retval) from anywhere in its call chain, not only the start routine:
static void fail_fast(void)
{
pthread_exit((void *)(intptr_t)-2);
}Calling it unwinds the thread's cleanup handlers and any thread-specific data destructors, then makes retval available to the joiner. It is rarely needed in C, since returning does the same, and in C++ it interacts badly with destructors on glibc because it unwinds the stack with a forced-unwind exception. Prefer returning.
Choosing a pattern
| Situation | Use |
|---|---|
| Several inputs or outputs | A struct per thread, owned by the creator |
| One small non-negative integer | (void *)(intptr_t)value |
| A result whose size the thread decides | Heap allocation, freed by the joiner |
| A result needed before the thread ends | A shared structure plus synchronization, not the join |
| Many tasks, results needed as they finish | A thread pool with a queue |
The last two rows mark the limit of the join-based approach: the return value only arrives when the thread has finished. For streaming results you need a queue protected by a mutex and a condition variable.
Passing ownership with a heap argument
The struct-per-thread pattern works when the creator outlives the thread. For a thread that may outlive its creator, such as a detached worker, pass ownership instead. The creator allocates the argument, hands it over and forgets it; the thread frees it when done:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct task {
char name[16];
int repeat;
};
static void *run(void *arg)
{
struct task *task = arg;
for (int i = 0; i < task->repeat; i++)
printf("%s: step %d\n", task->name, i + 1);
free(task);
return NULL;
}
int main(void)
{
struct task *task = malloc(sizeof *task);
if (task == NULL)
return 1;
strcpy(task->name, "indexer");
task->repeat = 2;
pthread_t t;
int rc = pthread_create(&t, NULL, run, task);
if (rc != 0) {
free(task);
return 1;
}
pthread_join(t, NULL);
return 0;
}indexer: step 1
indexer: step 2The rule is that exactly one side frees the argument. If pthread_create fails, the creator still owns it and frees it, which the rc != 0 branch does. If it succeeds, the thread owns it from the first instruction. Mixing the two, for example freeing in the creator after a successful create, is a use-after-free race against the new thread.
Reading the result safely
One more habit prevents a class of crashes: check the return value of the join and the pointer you get back before using either. pthread_join returns an error number, and it can return ESRCH if the handle is not a live thread or EINVAL if the thread is detached, in which case the result pointer is untouched. Initialize the receiving variable to NULL before the call, so that a failed join leaves a value you can test, and treat PTHREAD_CANCELED as a separate outcome from NULL. A worker that failed should report it through its result struct, with an error field the creator checks after the join, rather than through a magic pointer value that is easy to confuse with success.


