Pass integer value through pthread_create

前端 未结 4 765
感动是毒
感动是毒 2020-11-28 14:56

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;          


        
相关标签:
4条回答
  • 2020-11-28 15:12

    It better to use of a struct for send more parameters in one :

    struct PARAMS
    {
        int i;
        char c[255];
        float f;
    } params;
    
    pthread_create(&thread_id, NULL, fun, (void*)(&params));
    

    then you can cast params to PARAMS* and use of it in pthread routine:

    PARAMS *p = static_cast<PARAMS*>(params);
    p->i = 5;
    strcpy(p->c, "hello");
    p->f = 45.2;
    
    0 讨论(0)
  • 2020-11-28 15:13

    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.

    0 讨论(0)
  • 2020-11-28 15:14

    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;
    
    0 讨论(0)
  • 2020-11-28 15:32
    void *foo(void *i) {
        int a = *((int *) i);
        free(i);
    }
    
    int main {
        int *arg = (char*)malloc(sizeof(char))
        pthread_create(&thread, 0, foo, arg);
    }
    
    0 讨论(0)
提交回复
热议问题