Pass integer value through pthread_create

The compiler will complain if you don’t cast i to a void pointer:

pthread_create(&thread_tid[i], NULL, collector, (void*)i);

That said, casting an integer to a pointer isn’t strictly safe:

ISO/IEC 9899:201x
6.3.2.3 Pointers

  1. An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

so you’re better off passing a separate pointer to each thread.

Here’s a full working example, which passes each thread a pointer to a separate element in an array:

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

void * collector(void* arg)
{
    int* a = (int*)arg;
    printf("%d\n", *a);
    return NULL;
}

int main()
{
    int i, id[10];
    pthread_t thread_tid[10];

    for(i = 0; i < 10; i++) {
        id[i] = i;
        pthread_create(&thread_tid[i], NULL, collector, (void*)(id + i));
    }

    for(i = 0; i < 10; i++) {
        pthread_join(thread_tid[i], NULL);
    }

    return 0;
}

There’s a nice intro to pthreads here.

Leave a Comment