调用线程时出错:expect'void *(*)(void *)'但参数是类型

时间:2016-10-26 17:43:58

标签: c multithreading pthreads

我有一个在C中定义的结构

var fooObj: foo = {
    bar() {
        console.log(this.baz);
    }
}

我有一个打印高度和宽度的功能

typedef struct shape{
   int height;
   int width;

} rectangle;

// just to denote the rectangles where width > height
typedef rectangle wider;

wider all[3]={{5,10},{2,4},{7,9}};

现在我想通过创建线程为每个形状实现这一点,所以我尝试了这个:

void funct(wider shape){
printf("height: %d, width %d", shape.height, shape.width);
}

但是,这显示错误

pthread_t threads[sizeof(all)];
int count=0;
for(count=0; count <sizeof(all);++count)
{
  if(pthread_create(&threads[count], NULL, funct,(wider*)all[count])!=0)
    {
    printf("Error in creating thread: %d",count);
   break;
    }
}

int i=0;
for(i=0; i<count; ++i)
{
if(pthread_join(threads[i],NULL)!=0)
  printf ("Eroor joining: %d"+i);
}

我尝试将我的功能更改为

expected 'void * (*)(void *)' but argument is of type 'void (*)(struct rectangle)'

但这仍然不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:1)

pthread_create()期望一个函数参数以void*作为输入并返回void*。但是你的功能都没有。因此,编译器抱怨类型不匹配。

改为改变功能:

void* funct(void *arg){
   wider shape = *(wider*)arg;
   printf("height: %d, width %d", shape.height, shape.width);
   return NULL;
}

你的论点传递有另一个问题。您没有传递all[count]的地址,而是将wider转换为void*。您的sizeof计算也是错误的。您应该除以sizeof(all[0])以获得wider数组中正确数量的all元素。

pthread_t threads[sizeof(all)/sizeof(all[0])];
int count=0;
for(count=0; count <sizeof(all)/sizeof(all[0]);++count)
{
  if(pthread_create(&threads[count], NULL, funct,&all[count])!=0)
    {
       printf("Error in creating thread: %d",count);
       break;
    }
}