Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass integer value through pthread_create

Tags:

c

pthreads

I simply want to pass the value of an integer to a thread.

How can I do that?

I tried:

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

The thread method looks like this:

    void *collector( void *arg)
    {
        int a = (int) arg;
    ...

I get the following warning:

    warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
like image 799
Rui Vaz Avatar asked Oct 26 '13 02:10

Rui Vaz


2 Answers

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.

like image 62
Tom Fenech Avatar answered Oct 11 '22 15:10

Tom Fenech


int is 32 bit, and void * is 64 bit in 64bit Linux; In that case you should use long int instead of int;

long int i;
pthread_create(&thread_id, NULL, fun, (void*)i);

int fun(void *i) function

 long int id = (long int) i;
like image 31
neouyghur Avatar answered Oct 11 '22 14:10

neouyghur