Course contentsShow
← C
Lesson 1120 of 1,21915. Systems ProgrammingFree lesson

Returning values from threads

Returning values from threads

What you'll learn: How to pass data back from a background thread to your main program using the pthread_join function.

The Post Office Analogy

Think of a thread like a specialized contractor you hire to perform a task. When you start the thread (pthread_create), you send them off to their workshop. However, a contractor doesn't just finish and vanish; they usually produce a result—like a finished chair or a report. To get that result, you must wait for them to return and hand it over. In C, pthread_join is the act of waiting at the door for your contractor to arrive with the goods.

Using void** to catch data

In previous lessons, we used pthread_join(thread_id, NULL) to simply wait for a thread to die. To actually get data back, we replace NULL with the address of a pointer.

Because pthreads is designed to be flexible, it communicates using void * (a generic pointer). When the thread finishes, it "returns" a pointer. To capture that pointer in our main function, we provide the address of our own pointer, effectively creating a "double pointer" (void **).

Code Example: Calculating a Square

Here is how a thread can calculate a value and hand it back to the main process.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void* calculate_square(void* arg) {
    int num = *(int*)arg;
    int* result = malloc(sizeof(int)); // Allocate memory for the result
    *result = num * num;
    
    // The value we return here is what pthread_join will capture
    return (void*)result;
}

int main() {
    pthread_t thread;
    int input = 5;
    int* exit_value;

    pthread_create(&thread, NULL, calculate_square, &input);

    // Wait for the thread and capture its return value into exit_value
    pthread_join(thread, (void**)&exit_value);

    printf("The thread returned: %d\n", *exit_value);

    free(exit_value); // Clean up the memory allocated inside the thread
    return 0;
}

A Vital Warning: Watch the Scope

One common mistake is returning a pointer to a local variable created inside the thread function. Local variables live on the "stack" and disappear the moment the thread finishes. If you return a pointer to a local variable, your main program will receive a "dangling pointer" to garbage memory.

To safely return data, you should either:

  1. Use malloc to put the result on the heap (as shown above).
  2. Pass a pointer to a pre-allocated buffer into the thread as an argument.

Key takeaway

To retrieve data from a thread, use pthread_join with a void** argument to capture the pointer returned by the thread's entry function.