【发布时间】:2017-01-27 17:19:05
【问题描述】:
我在尝试向 pthread_create 发送多个参数时遇到问题,问题基本上是因为其中一个参数是另一个结构。
这是节点。
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#define NUM_THREADS 4
struct arr {
char line[10];
};
struct args {
struct arr record; int count; int init; int end;
};
void* processarr(void *arguments)
{
int count; int init; int end;
struct args *argstmp=arguments;
init=argstmp->init;
count=argstmp->count;
end=argstmp->end;
struct arr record[count];
record=(struct arr)argstmp->record;
printf("Some of the vals are init %d count %d end %d\n",init, count, end);
printf("vals like record 0\n", record[0].line);
pthread_exit(NULL);
}/*end of processarr*/
int main (int argc, char *argv[])
{
int line_count;
FILE *ptr_file;
char buf[10];
ptr_file =fopen(argv[ 1 ],"r");
if (!ptr_file)
return 1;
while (fgets(buf,10, ptr_file)!=NULL)
{
line_count++ ;
}
rewind(ptr_file);
struct arr record[line_count];
line_count=0;
while (fgets(buf,10, ptr_file)!=NULL)
{
line_count++ ;
buf[strcspn(buf, "\r\n")] = 0; /* Removing end null chars*/
strcpy(record[line_count].line,buf);
}
float grptmp,group, lgroup;
grptmp=line_count/NUM_THREADS;
int counter1,counter2,init,end;
counter2=1;
struct args myargs;
//processarr(record, line_count, init, end);
pthread_t threads[NUM_THREADS];
for (counter1=0;counter1<=line_count;counter1++)
{
if(counter2==NUM_THREADS)
{
end=line_count;
}else{
end=counter1+grptmp;
}
init=counter1;
myargs.record=*record;
myargs.count=line_count;
myargs.init=init;
myargs.end=end;
printf ("Run job #%d with paramts Init=%d and End=%d\n",counter2, init, end);
//call here
//struct arr *record; int count; int init; int end;
int rc;
long t;
for(t=0;t<NUM_THREADS;t++){
rc = pthread_create(&threads[t], NULL,processarr,&myargs);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
counter1=counter1+grptmp;
counter2++;
}
return 0;
}
因此,当我发送参数时,存储在 myargs.record=*record 中的参数,由于某种原因,我无法在函数中“解压”一次。
该函数被定义为 void 以便能够捕获整个大参数,我正在尝试重新映射那里的所有内容,计数工作正常,但称为记录的那个实际上是另一个结构不是工作,看起来像演员表问题。
void* processarr(void *arguments)
{
int count; int init; int end;
struct args *argstmp=arguments;
init=argstmp->init;
count=argstmp->count;
end=argstmp->end;
struct arr record[count];
record=(struct arr)argstmp->record;
printf("Some of the vals are init %d count %d end %d\n",init, count, end);
printf("vals like record 0\n", record[0].line);
pthread_exit(NULL);
}
编译时出现以下错误。
test4.c: In function processarr:
test4.c:31:7: error: assignment to expression with array type
record=(struct arr)argstmp->record;
知道为什么这不起作用吗?最后一个是我在 argstmp(应该包含所有内容)前面使用强制转换(struct arr)的最后一次更改。
【问题讨论】:
-
record=(struct arr)argstmp->record;错误信息很清楚。您不能使用赋值运算符复制数组。而且这些类型无论如何都不兼容。struct arr record[count];是一个数组,但argstmp->record是一个结构体。 -
拒绝阅读代码。请正确缩进。
-
嘿马特,我不会像你使用它们的方式使用参数,我会做这样的事情,创建一个参数结构,你可以从 pthread 创建和解包一次在那里,那么你不会有任何铸造问题。
-
嗨@Marco,这似乎是我会尝试的选项。
-
顺便说一句,我们是来帮助@alk的,“拒绝阅读代码”是什么意思?如果这将是您的输入,您最好不要评论,代码就是代码,无论它看起来多么漂亮,只需在其上运行美化器。