Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

c - Pass integer value through pthread_create

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", *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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...