0
我在嘗試向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 = *記錄的人,出於某種原因,我沒能在功能,一旦「解包」吧。
該函數被定義爲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前面使用cast(struct arr)的最後一次更改(它應該包含所有內容)。
'record =(struct arr)argstmp-> record;'錯誤信息很清楚。您不能使用賦值運算符複製數組。無論如何,這些類型都不兼容。 'struct arr record [count];'是一個數組,但'argstmp-> record'是一個單獨的結構。 – kaylum
拒絕閱讀代碼。請正確縮進。 – alk
嘿馬特,我不會用你使用它們的方式來使用參數,我會改爲做這樣的事情,創建一個參數結構體,你可以從pthread中創建和解包一次,然後你不會將會與鑄件有任何問題。 – Marco