#include <pthread.h>
#include <stdio.h>
typedef struct {
int id;
char *filename;
float sum;
float dif;
} child;
void *calData(void *argv){
child *tempChild = (child *) argv;
FILE *fp;
int id = tempChild->id;
float max, min,buffer, sum , dif;
if(fopen(tempChild->filename, "r") == NULL) {
printf("Fail to open file");
exit(1);
}
fp = fopen(tempChild->filename, "r");
fscanf(fp, "%f", &buffer);
/* initialize the max and min */
max = buffer;
min = buffer;
/* scan every element in the dataset */
while(!feof(fp)) {
fscanf(fp, "%f", &buffer);
if(buffer <= min) {
min = buffer;
}
if(buffer >= max) {
max = buffer;
}
}
fclose(fp);
/* pass the calculted results to child */
sum = max + min;
dif = max - min;
tempChild->sum = sum;
tempChild->dif = dif;
printf("%.5f %.5f %.5fn", sum, dif, id);
}
int main(int argc, char **argv){
/* initialize the of memory size of threads and children */
pthread_t *threads;
threads = (pthread_t *) malloc((argc-1) * sizeof(*threads));
child *children;
children = (child *) malloc((sizeof(child)) * (argc - 1));
int i, j;
/* start the threads */
for(i=0; i < (argc - 1); i++)
{
children[i].id = i;
children[i].filename = argv[i+1];
pthread_create(threads+i, NULL, calData, (void *)children+i);
}
/* Synchronize the completion of each thread. */
for(j=0; j < (argc-1); j++){
pthread_join(threads[j], NULL);
}
printf("%.5f %.5f n",children[0].sum, children[0].dif);
}
嗨,我正在学习pthread。这是一个问题,正如你在代码中看到的那样,输入应该由3个txt文件组成,我想处理它们,并通过pthread获得sum和dif。然而,有一个输入参数是可以的,但当我尝试输入3个数据文件时,它一直说"无法打开文件"。
我搜索到我可能需要一些关于互斥的帮助,有人能告诉我如何修复它吗?
这是显而易见的第一个问题:
pthread_create(threads+i, NULL, calData, (void *)children+i);
检查C中的操作优先级,并将其替换为:
pthread_create(threads+i, NULL, calData, (void *)(children + i));
您的地址ariphmetics +
运算符的优先级低于(void *)
类型强制转换,因此children
递增i
字节,而不是i
child
结构大小。
但实际上,如果您的C编译器允许,我建议您在这种情况下从指针切换到数组。更安全,所以这是你的主要((:
int main(int argc, char **argv){
pthread_t threads[argc -1];
child children[argc - 1];
int i, j;
/* start the threads */
for(i=0; i < (argc - 1); i++)
{
children[i].id = i;
children[i].filename = argv[i+1];
pthread_create(&threads[i], NULL, calData, &children[i]);
}
/* Synchronize the completion of each thread. */
for(j=0; j < (argc-1); j++){
pthread_join(threads[j], NULL);
}
printf("%.5f %.5f n",children[0].sum, children[0].dif);
}
我怀疑问题在于如何将参数传递给线程:
pthread_create(threads+i, NULL, calData, (void *)children+i);
由于强制转换运算符的优先级高于+
,因此先将children
强制转换为void*
,然后添加i
(注意,gcc允许对空指针进行指针运算(。导致除第一个线程外的指针值不正确。
请尝试:
pthread_create(threads+i, NULL, calData, (void *)(children+i));
或
pthread_create(threads+i, NULL, calData, (void *)&children[i]);
其他问题:
- 不要将
malloc
的返回值大小写。这有潜在的危险 while(!feof(fp)) {
几乎肯定不是你想要的。你的循环会比你想要的多运行一次。请参阅为什么"while(!feof(file(("总是错误的