通过pthread_create传递整数值

通过pthread_create传递整数值,c,pthreads,C,Pthreads,我只想把一个整数的值传递给一个线程 我该怎么做 我试过: int i; pthread_t thread_tid[10]; for(i=0; i<10; i++) { pthread_create(&thread_tid[i], NULL, collector, i); } 我得到以下警告: warning: cast from pointer to integer of different size [-Wpoin

我只想把一个整数的值传递给一个线程

我该怎么做

我试过:

    int i;
    pthread_t thread_tid[10];
    for(i=0; i<10; i++)
    {
        pthread_create(&thread_tid[i], NULL, collector, i);
    }
我得到以下警告:

    warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

如果您没有将
i
强制转换为空指针,编译器会抱怨:

pthread_create(&thread_tid[i], NULL, collector, (void*)i);
也就是说,将整数强制转换为指针并不是绝对安全的:

ISO/IEC 9899:201x 6.3.2.3指针

  • 整数可以转换为任何指针类型。除非前面指定,否则结果是实现定义的,可能没有正确对齐,可能没有指向引用类型的实体,并且可能是陷阱表示 因此,最好向每个线程传递一个单独的指针

    下面是一个完整的工作示例,它向每个线程传递一个指向数组中单独元素的指针:

    #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;
    }
    
    #包括
    #包括
    void*收集器(void*arg)
    {
    int*a=(int*)arg;
    printf(“%d\n”,*a);
    返回NULL;
    }
    int main()
    {
    int i,id[10];
    pthread_t thread_tid[10];
    对于(i=0;i<10;i++){
    id[i]=i;
    pthread_create(&thread_tid[i],NULL,收集器,(void*)(id+i));
    }
    对于(i=0;i<10;i++){
    pthread_join(thread_tid[i],NULL);
    }
    返回0;
    }
    

    pthreads有一个很好的介绍。

    int是32位的,void*在64位Linux中是64位的;在这种情况下,应该使用long int而不是int

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


    最好使用
    struct
    一次发送更多参数:

    struct PARAMS
    {
        int i;
        char c[255];
        float f;
    } params;
    
    pthread_create(&thread_id, NULL, fun, (void*)(&params));
    
    然后您可以
    参数
    转换为
    参数*
    ,并在
    pthread
    例程中使用它:

    PARAMS *p = static_cast<PARAMS*>(params);
    p->i = 5;
    strcpy(p->c, "hello");
    p->f = 45.2;
    
    PARAMS*p=static_cast(PARAMS);
    p->i=5;
    strcpy(p->c,“你好”);
    p->f=45.2;
    
    不适合我。获取了未初始化的索引。这完成了任务:pthread_create(&thread_tid[i],NULL,collector,(void*)(id[i])<代码>malloc
    缺失
    void *foo(void *i) {
        int a = *((int *) i);
        free(i);
    }
    
    int main {
        int *arg = (char*)malloc(sizeof(char))
        pthread_create(&thread, 0, foo, arg);
    }
    
    struct PARAMS
    {
        int i;
        char c[255];
        float f;
    } params;
    
    pthread_create(&thread_id, NULL, fun, (void*)(&params));
    
    PARAMS *p = static_cast<PARAMS*>(params);
    p->i = 5;
    strcpy(p->c, "hello");
    p->f = 45.2;