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

Passing arguments to threads

Passing arguments to threads

What you'll learn: How to securely pass data from your main program into a new thread using a single pointer.

The Mailbox Problem

When you create a thread using pthread_create, you are essentially hiring a new worker to run a function. However, the pthread API is designed to be universal, meaning it doesn't know in advance what kind of data your specific function needs. To solve this, the API uses a "one-size-fits-all" mailbox: a single void * (void pointer).

Think of a void * as a blank shipping label. You can stick it on any box—an integer, a struct, or an array—and send it to the thread. The thread then "casts" that label back to the correct type to see what’s inside.

Packing and Unpacking

Because pthread_create only accepts one argument, if you need to pass multiple pieces of information (like a username and a user ID), you should wrap them in a struct. Even for a single integer, you must pass its address and tell the thread how to interpret that memory.

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

struct thread_data {
    int thread_id;
    char *message;
};

void* print_hello(void* arg) {
    // Unpacking: Cast the void pointer back to our struct type
    struct thread_data *data = (struct thread_data *)arg;
    
    printf("Thread %d says: %s\n", data->thread_id, data->message);
    
    return NULL;
}

int main() {
    pthread_t thread;
    struct thread_data my_args;

    my_args.thread_id = 1;
    my_args.message = "Hello from the main ship!";

    // Passing the address of our struct as a void pointer
    pthread_create(&thread, NULL, print_hello, (void *)&my_args);

    pthread_join(thread, NULL);
    return 0;
}

The Memory Trap

The biggest mistake beginners make is passing the address of a variable that changes or disappears. If you pass the address of a loop counter (&i) and the loop continues to increment, the thread might read the "new" value of i before it even starts.

Always ensure the data you pass stays valid for the entire life of the thread. Using a struct on the heap (via malloc) or a stable local variable in main (as shown above) ensures your thread isn't reading "junk" memory.

Key takeaway

To pass data to a thread, pack your variables into a struct and pass its address as a void *, then cast it back to the original type inside the thread function.