【问题标题】:Pass integer value through pthread_create通过 pthread_create 传递整数值
【发布时间】:2013-11-05 06:59:00
【问题描述】:

我只是想将整数的值传递给线程。

我该怎么做?

我试过了:

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

线程方法如下所示:

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

我收到以下警告:

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

【问题讨论】:

    标签: c pthreads


    【解决方案1】:

    如果您不将 i 转换为 void 指针,编译器会报错:

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

    也就是说,将整数转换为指针并不是严格安全的:

    ISO/IEC 9899:201x 6.3.2.3 指针

    1. 整数可以转换为任何指针类型。除非前面指定,结果是实现定义的,可能没有正确对齐,可能不指向引用类型的实体,并且可能是陷阱表示。

    所以你最好将一个单独的指针传递给每个线程。

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

    #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;
    }
    

    pthreads here 有一个很好的介绍。

    【讨论】:

    • 对我不起作用。得到未初始化的索引。但这确实完成了工作: pthread_create(&thread_tid[i], NULL, collector, (void*)(id[i]));
    【解决方案2】:

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

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

    int fun(void *i) 函数

     long int id = (long int) i;
    

    【讨论】:

      【解决方案3】:
      void *foo(void *i) {
          int a = *((int *) i);
          free(i);
      }
      
      int main {
          int *arg = (char*)malloc(sizeof(char))
          pthread_create(&thread, 0, foo, arg);
      }
      

      【讨论】:

      • malloc 丢失
      【解决方案4】:

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

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

      那么你可以castparamsPARAMS*并在pthreadroutine中使用它:

      PARAMS *p = static_cast<PARAMS*>(params);
      p->i = 5;
      strcpy(p->c, "hello");
      p->f = 45.2;
      

      【讨论】:

        猜你喜欢
        • 2020-01-21
        • 1970-01-01
        • 1970-01-01
        • 2018-05-10
        • 1970-01-01
        • 2018-10-15
        • 1970-01-01
        • 2010-12-31
        • 2021-11-18
        相关资源
        最近更新 更多